2๐
โ
I have found a solution, using Count, Case and IntegerField:
user_id = self.request.user.pk
queryset = Product.objects \
.annotate(favorited=Count(Case(When(favorited_by__user__pk=user_id, then=1), output_field=IntegerField()))) \
.order_by("-favorited")
๐คR. Wenger
Source:stackexchange.com