Django Computed Values


Example

Once a model object has been fetched, it becomes a fully realized instance of the class. As such, any additional methods can be accessed in forms and serializers (like Django Rest Framework).

Using python properties is an elegant way to represent additional values that are not stored in the database due to varying circumstances.

def expire():
    return timezone.now() + timezone.timedelta(days=7)

class Coupon(models.Model):
    expiration_date = models.DateField(default=expire)

    @property
    def is_expired(self):
        return timezone.now() > self.expiration_date

While most cases you can supplement data with annotations on your querysets, computed values as model properties are ideal for computations that can not be evaluated simply within the scope of a query.

Additionally, properties, since they are declared on the python class and not as part of the schema, are not available for querying against.