3 ms·
Django will do something similar (possibly a little more elegantly) if one is familiar with how to use the Prefetch APIs [1]: Post.objects.order_by("-creat
by VWWHFSfQ 4y ago
Django will do something similar (possibly a little more elegantly) if one is familiar with how to use the Prefetch APIs [1]:
Post.objects.order_by("-created_at").prefetch_related(
Prefetch(
"comments",
queryset=Comment.objects.annotate(
vote_count=Count("votes")
),
)
)[:3]
This will generate the following two queries:
SELECT
"post"."id",
"post"."created_at",
"post"."title",
"post"."content"
FROM "post"
ORDER BY "post"."created_at" DESC
LIMIT 3;
SELECT
"comment"."id",
"comment"."post_id",
"comment"."content",
COUNT("vote"."id") AS "vote_count"
FROM "comment"
LEFT OUTER JOIN "vote"
ON ("comment"."id" = "vote"."comment_id")
WHERE "comment"."post_id" IN (3, 2, 1)
GROUP BY
"comment"."id",
"comment"."post_id"
[1] https://docs.djangoproject.com/en/4.1/ref/models/querysets/#django.db.models.Prefetch https://docs.djangoproject.com/en/4.1/ref/models/querysets/#...
- chc 4y agoPersonally, I find the Rails version a bit more elegant because it is declarative, reusable and composable, while Django's approach is a more utilitarian "just write the dang query when you want it." But both are a great illustration of how a well-designed ORM can give you the tools you need to get good performance.
- saila 4y agoYou can do the same kind of thing in Django. The approach is a little different, but it's the same basic idea. https://docs.djangoproject.com/en/4.1/topics/db/managers/#custom-managers https://docs.djangoproject.com/en/4.1/topics/db/managers/#cu...