5.10. Models Method PropertyΒΆ

  • @property is a Python decorator that allows you to define a method that behaves like an attribute

  • This fields are not stored in the database

  • They are calculated when accessed

  • They are read-only (can't be set)

  • They can be used in the Django Admin

>>> 
... from datetime import date
... from django.db import models
... from django.utils.translation import gettext_lazy as _
... from shop.models import Address, Email
...
...
... YEAR = 365.25
...
...
... class Customer(models.Model):
...     firstname = models.CharField(verbose_name=_('First Name'), max_length=100, null=False, blank=False)
...     lastname = models.CharField(verbose_name=_('Last Name'), max_length=100, null=False, blank=False, db_index=True)
...
...     @property
...     def age(self):
...         days = (date.today() - self.birthdate).days
...         return int(days / YEAR)
...
...     @property
...     def emails(self):
...         return Email.objects.filter(customer=self)
...
...     @property
...     def addresses(self):
...         return Address.objects.filter(customer=self)
...
...     @property
...     def changelog(self):
...         from django.contrib.contenttypes.models import ContentType
...         from django.contrib.admin.models import LogEntry
...         model = self.__class__.__name__.lower()
...         ct = ContentType.objects.get(app_label='contact', model=model)
...         return LogEntry.objects.filter(content_type=ct, object_id=self.pk)
...
...     def __str__(self):
...         return f'{self.firstname} {self.lastname}'
...
...     class Meta:
...         verbose_name = _('Customer')
...         verbose_name_plural = _('Customers')