djangocachingdjango-caching

How Can I Verify that Django @cached_property is Working (caching)?


In the below example, I have questions.

Example

from django.utils.functional import cached_property

class Product(models.Model):
    class ProductType(models.TextChoices):
        PRODUCT = 'PRODUCT', _('Product')
        LISTING = 'LISTING', _('Listing')

    my_model = models.ForeignKey(MyModel, on_delete=models.CASCADE, related_name='products')
    product_type = models.CharField(max_length=7, choices=ProductType.choices)

class MyModel(models.Model):
    ...
    
    @cached_property
    def listing(self):
        return self.products.get(product_type=Product.ProductType.LISTING)

Questions

  1. Is the listing property being cached on the MyModel object? I ask because it's accessing .get() of a queryset which has greater implications.

Ex:

instance = MyModel()
instance.listing # hits db
instance.listing # gets from cache?
  1. How can I set up a scenario to inspect and verify that caching of instance.listing is in-fact happening? I read to look in the __dict__ method of instance.listing.__dict__ but I don't notice anything specific.

Solution

  • If you read source of this decorator https://docs.djangoproject.com/en/4.0/_modules/django/utils/functional/#cached_property you will see that you are probably checking this in wrong place. listing will be cached on the instance itself, meaning you need to check instance.__dict__.