In Django models, static
methods can also be added. These methods can directly be called using the Model's name. There is no need to create an object in order to access the method.
For example, lets add the static method inside the Person
model.
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)
email = models.EmailField(unique=True, null=True)
username = models.CharField(max_length=30,unique=True, null=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
class Meta:
unique_together = ('first_name', '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
@staticmethod
def get_persons_by_dob():
return Person.objects.all().order_by('birth_date')
Now you can call the get_persons_by_dob()
method, without creating the object of the Person class.
from modeldemo.models import Person
Person.get_persons_by_dob()
Similarly static methods
can also be created with parameters.
@staticmethod
def get_persons(startswith=''):
return Person.objects.filter(first_name__startswith=startswith)
If the startswith parameter is given, then it will return the values with wich the name starts, else it will return all the person objects.
Without Parameter :
from modeldemo.models import Person
Person.get_persons()
With Parameter :
Person.get_persons('J')