Skip to content

Using @property with @cache_memoize #76

@isaac-blanc

Description

@isaac-blanc

Question

The examples in the docs are for pure functions. Does this library work with model methods?

from django.db import models
from cache_memoize import cache_memoize

class Demo(models.Model):
    
    pk = models.AutoField(primary_key=True)
    A = models.FloatField()
    B = models.FloatField()

    def __str__(self):
        return str(self.pk)

    @property
    @cache_memoize(100)
    def expensive(self):
        return self.A * self.B

Research

I've trialled this and it seems to work fine. Of course, the first argument of any method is self, which refers to an instance of the model class. Therefore, as already mentioned in the docs, the model __str__() method must return a unique string. It's easy enough to ensure that. In the example above, I have set the __str__() method to return the object primary key, but there are plenty of other ways to produce something unique.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions