The Python Oracle

Order a django queryset by ManyToManyField = Value

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC M Beethoven - Piano Sonata No 3 in C 3

--

Chapters
00:00 Question
02:26 Accepted answer (Score 6)
03:06 Thank you

--

Full question
https://stackoverflow.com/questions/3703...

Accepted answer links:
[conditional]: https://docs.djangoproject.com/en/1.9/re.../

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #djangomodels

#avk47



ACCEPTED ANSWER

Score 6


I'd try annotate the query with the conditional value that turns true when the tag is in the list you provide

from django.db.models import Case, When, IntegerField

Thing.objects.annotate(tag_is_known=Case(
    When(tags__name__in=['foo', 'bar'], then=1),
    default=0,
    output_field=IntegerField()
))

Next we use that annotation we called tag_is_known to sort with order_by():

Thing.objects.annotate(tag_is_known=...).order_by('tag_is_known')

Boolean version

Thing.objects.annotate(tag_is_known=Case(
    When(tags__name__in=['foo', 'bar'], then=True),
    default=False,
    output_field=BooleanField()
))