Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I have never encountered this issue in Django. Perhaps your post lacks some context. Is `friends` a custom method/property? Asking because I'm used to seeing attributes like `friends_set`.

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.


Based on context, GP's example is a ManyToMany field. "friend_set" is what you'd get on a reverse ForeignKey or reverse ManyToMany by default, but can be changed with the "related_name" kwarg.

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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: