4.11. Models Method Property
@property
is a Python decorator that allows you to define a method that behaves like an attributeThis 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
...
...
... 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, year=365.25):
... 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()
... app_label = self.__class__._meta.app_label
... ct = ContentType.objects.get(app_label=app_label, 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')