In the previous topic, you saw how you can update the records of persons who were born before 1960. Now, if any new record is added or the birth_date
of any previous record is updated, you will need to run the update()
to set is_active
to False everytime. This is not an eficient way to update()
the records. There is an alternate way to update the records which is to override the default save()
method. By this, any time if a new object is created or an existing object is updated, it will check the birth_date
and update the is_active
field accordingly. The save()
method can be overrided as follows :
from datetime import datetime
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
birth_date = models.DateField()
is_active = models.BooleanField(default=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
def save(self, *args, **kwargs):
if isinstance(self.birth_date, str):
self.birth_date = datetime.strptime(self.birth_date, '%Y-%m-%d').date()
if self.birth_date.year<1960:
self.is_active=False
super().save(*args, **kwargs)
So here, first if the argument is of string type, it is converted into date and then if the year is less than 1960, the is_active
field is updated to False
and then the default save()
method of the model is called.
So now, if you create a new object or update any existing object, according to the condition the is_active
field would be changed automatically. For example, change the birth_date
field where id=1 :
p=Person.objects.get(id=1)
p.birth_date = '1959-01-01'
p.save()
As you can see, the is_active
column on calling the save()
method is updated automatically when the birth_date
value changes.