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
- Is the
listingproperty being cached on theMyModelobject? 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?
- How can I set up a scenario to inspect and verify that caching of
instance.listingis in-fact happening? I read to look in the__dict__method ofinstance.listing.__dict__but I don't notice anything specific.
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.
listingwill be cached on the instance itself, meaning you need to checkinstance.__dict__.