[Answered ]-Django Rest Framework: Order by user dependent field

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

Leave a comment