The Python Oracle

Order a django queryset by ManyToManyField = Value

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World

--

Chapters
00:00 Order A Django Queryset By Manytomanyfield = Value
02:02 Accepted Answer Score 6
02:31 Thank you

--

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

--

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()
))