1👍
✅
If just setting distinct=True
doesn’t work, then you can use subqueries, as shown in Serafim’s answer here. Given that you mention Vote and Post are a many-to-many relation, you could rewrite e.g. my_votes
as a subquery on the through table, something like:
def get_queryset(self):
my_votes_sq = Subquery(
Vote.posts.through.objects
.filter(post_id=OuterRef("pk"), user_id=self.request.user.id)
.order_by()
.values("post_id")
.annotate(count=Count("pk"))
.values("count"), output_field=IntegerField()
)
...
return self.queryset.annotate(
my_votes=Coalesce(my_votes_sq, 0),
...
)
The actual field names for posts
, post_id
, user_id
will depend on your models of course.
Source:stackexchange.com