Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

property decorator eager load and eager load in general using Django

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

like image 257
Pietro Avatar asked Feb 04 '26 05:02

Pietro


2 Answers

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.

like image 67
Jason S Avatar answered Feb 05 '26 21:02

Jason S


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/

like image 31
Mia Avatar answered Feb 05 '26 20:02

Mia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!