nandesuka
nandesuka

Reputation: 799

Change BooleanField whenever object is updated

I have a model with an property called changed which I'd like to change to True when the model is changed. But ofcourse I don't want to set it to True on the creation of an object.

class SomeModel(models.Model):
  changed = models.BooleanField(default=False, blank=True, null=True)

Upvotes: 0

Views: 64

Answers (2)

nOperator
nOperator

Reputation: 131

Overwrite the save method

class SomeModel(models.Model):
  changed = models.BooleanField(default=False) # no need to use null=True, it would add a third possibility to the boolean (null, True, False) but you could use: 
  # changed = models.BooleanField(default=False, editable=False)
  
  def save(self, *args, **kwargs):
    if self._state.adding is False:
      self.changed = True
    super().save(*args, **kwargs)

Edit: fixed typo from self._state to self._state.adding

Upvotes: 1

Shamir Imtiaz
Shamir Imtiaz

Reputation: 183

" on the creation of an object." I don't understand this properly. But I assume by default you want to set it null. If so then:

changed = models.BooleanField(default=Null, blank=True, null=True)

Does this solve your issue?

Upvotes: 0

Related Questions