Django Models Computed Values

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


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.timedelta(days=7)

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

    def is_expired(self):
        return > 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.

Got any Django Question?