News for hackers. Stuff that matters.
Re:Understanding N + 1 queries problem by pphysch on Monday January 02, 2023 @04:18PM (#34223803)
It's pretty straightforward in Django. The key is being comfortable with writing custom Manager/QuerySet methods.

You could do something like `Post.objects.latest().annotate_comments()` which would resolve almost exactly to the query you wrote above.

Re:Understanding N + 1 queries problem by saila on Monday January 02, 2023 @05:50PM (#34224815)
Using a typical set of Post & Comment models, where Comment has a foreign key to Post, I couldn't figure out how to do this with just a single query in Django. Using prefetch_related, the 2-query version is pretty straightforward:

    from django.db.models import Count, Prefetch
    from myproject.models import Post, Comment

    # This will fetch the 3 posts first and then the comments for those posts
    query = Post.objects.prefetch_related(
        Prefetch("comments", queryset=Comment.objects.annotate(Count("votes")))
    )
    posts = query[:3]
How would you reduce this to one query using the Django ORM?
Re:Understanding N + 1 queries problem by pphysch on Tuesday January 03, 2023 @12:14PM (#34234339)
The previous query uses a JsonAgg to collect the comments