3 ms·
It's pretty straightforward in Django. The key is being comfortable with writing custom Manager/QuerySet methods. You could do something like `Post.objects.la
by pphysch 4y ago
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.
- saila 4y agoUsing 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?
- pphysch 4y agoThe previous query uses a JsonAgg to collect the comments
- deleted 4y ago[deleted]