[Django]-Django order_by many to many relation

3👍

Here’s one approach that can work, create a new field to sort by which maps your logical expression to a numerical value.

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

Publication.objects.annotate(
    ordering=Case(
        When(books__name="Awesome Book", then=Value(0)),
        default=Value(1),
        output_field=IntegerField(),
    )
).order_by("ordering")
👤NS0

Leave a comment