Ad

How Can I Define A Django Model's Field Default Value To Be Another Field Value?

In my model I have these two fields:

start_bid = models.IntegerField(default=0)
max_bid =  models.IntegerField(default="the start_bid value")

The start_bid will be added by the user once through Django ModelForm. And the max_bid may change and may not. So I need the first value of 'max_bid' to be the start_bid value entered by the user, then if it changes it will be updated.

In brief, I need the initial value of max_bid to be equal to the start_bid!

Any suggestions?

Ad

Answer

Overwrite save method on model.

def save(self, force_insert=False, force_update=False, using=None,  update_fields=None):  
        if self._state.adding: 
            self.max_bid = self.start_bid
        super().save(force_insert, force_update, using, update_fields)
Ad
source: stackoverflow.com
Ad