Search code examples
pythondjangodatabasedjango-modelsdefault-value

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?


Solution

  • 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)