To calculate or perform tasks, related to a model, you can create custom methods in it. For example, you want to calculate the age
of each Person
in the database. For this you can create a custom method and write a logic inside the method.
from django.db import models
from datetime import datetime, date
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
full_name = models.CharField(max_length=60, null=True)
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)
def calculate_age(self):
today = date.today()
age = today.year - self.birth_date.year
return age
The calculate_age()
method is added which returns the age
of the Person
based on the year. You can call the method as follows :
person = Person.objects.get(id=1)
person.calculate_age()
And similarly, this can be used on all Person
objects to get the age
of a Person
.