[Answered ]-Django order a query by instance of ManyToMany

1๐Ÿ‘

โœ…

As you already notice, you need to use a Subquery [Django docs] to annotate the weight. You can use OuterRef to refer to the outer queries b while filtering and also use Coalesce [Django docs] just in case to provide a default value:

from django.db.models import OuterRef, Subquery
from django.db.models.functions import Coalesce


weight_subquery = B2C.objects.filter(b=OuterRef('b'), c=given_c_instance)

queryset = A.objects.annotate(
    weight=Coalesce(Subquery(weight_subquery.values('weight')[:1]), 0)
).order_by('weight')

Leave a comment