by VWWHFSfQ · 5y ago · 0 comments
<ul>
{% for friend in user.friends.all %}
<li>{{ friend.name }}</li>
{% endfor %}
</ul>
The problem is that if you have 200 friends then it will make 200 queries. If you have 1,000,000 friends then, well, this will crash. The Django solution would be to fix-up your "user" queryset like: user = User.objects.filter(pk=<pk>).prefetch_related("friends").first()
Pay the query cost just once.. instead of on every iteration of the loop!Only in Rails it is far easier to accidentally introduce interfaces that do this: the downside of having a very easy DSL to quickly add relations between records/tables is that people very quickly add relations between records/tables: introduce spaghetti.
And in Rails it is very hard to debug, because ActiveRecord tries hard to be smart, but this "smart" quickly degrades into "black magic" when stuff gets complex (mostly caused by: see above, in my experience).
Edit: currently working on a codebase where 3000ms queries to get 200 items is no exception, where 500+ queries to build a page is common and where, if you change a foo on a bar, suddenly at the other end of the app, your blargs and blazzes start blurping out SQL that used to run 200ms but now adds some wheres and limits and group-bys that make it run over 2000ms. Yay for Rails trying to help!/s
There's a difference, however, between being aware of them and fixing them. Especially when they were caused by an unrelated change; when you cannot just roll back that change.
Except this was in a home-rolled solution which made it incredibly opaque where the ".friends" access actually happened (or if it wasn't ".acquaintances.where(type='friend')".
Made it very easy to get pages on the road, which just turned incredibly slow later down that same road, and fixing it wasn't trivial without knowing exactly what to preload when.
The only scenario I see where your example would need `prefetch_related` is if your snippet looked something like this:
{% for user in all_users %}
<ul>
{% for friend in user.friends.all %}
<li>{{ friend.name }}</li>
{% endfor %}
</ul>
{% endfor %}
To avoid the classic N+1 query problem, all_users must be loaded like so: User.objects.all().prefetch_related("friends")
If you're writing verbose expressions such as this in Django: User.objects.filter(pk=<pk>).prefetch_related("friends").first()
You must be doing something wrong.Either way you're right, GP's example as given doesn't have the 1+N problem (it's 1+1 at worst, a single query for user and a second single query for all friends), there's definitely missing context if they are seeing it.
See: https://docs.djangoproject.com/en/3.1/topics/db/queries/#cac...