Is it possible in Django to use eager loading for property decorator?
My code as example
class Player(models.Model):
roles = models.ManyToManyField(Role, related_name='players')
@property
def role(self):
return ", ".join([r.name for r in self.roles.all().order_by('name')])
When outputting the player role using the property, it runs a query each time.
Actually I still don't know how eager load works in general with Django. I can't find any good docs about it.
Thanks
This is a terminology issue. Django docs/source do not refer to "eager" loading as SQLAlchemy does. Instead, Django has select_related() and prefetch_related() filters for queries, which are documented in the QuerySet API reference.
But that is something you add to the query, not a declarative property. So you'd use prefetch_related('roles') when querying for the Player.
I'm not sure if this fits your needs, because this is useful for when you want to use the property of an instance several times, but Django has a @cached_property decorator which will cache the result of your property for as long as your instance exists.
More information if you do a quick ctrl+f in here:
https://docs.djangoproject.com/en/dev/ref/utils/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With