I visited http://guides.rubyonrails.org/active_record_querying.html after talking with a peer regarding N+1 and the serious performance implications of bad DB queries.
ActiveRecord (Rails):
clients = Client.includes(:address).limit(10)
Where client's have addresses, and I intend to access them while looping through the clients, Rails provides includes
to let it know to go ahead and add them to the query, which eliminates 9 queries right off the bat.
Django:
https://github.com/lilspikey/django-batch-select provides batch query support. Do you know of other libraries or tricks to achieve what Rails provides above, but in a less verbose manor (as in the rails example wherein just 19 chars fix N+1 and is very clear)? Also, does batch-select address the concern in the same way, or are these two different things?
BTW, I'm not asking about select_related
, though it may seem to be the answer at first glance. I'm speaking of a situation where address
has a forign key to client
.
You can do it with prefetch_related since Django 1.4: https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related
If you're using < 1.4, have a look at this module: https://github.com/ionelmc/django-prefetch
It claims to be more flexible than Django's prefetch_related. Verbose but works great.
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