Skip to content
Advertisement

Django order a query by instance of ManyToMany

I have a model A with a ForeignKey to B:

JavaScript

A ManyToMany relationship with an extra field that weight any B and C relation:

JavaScript

And I need to order the A model (A.objects.filter(…)) using the weight of B2C for a given instance of C.

For only one A instance I can do :

JavaScript

But I don’t know how to do apply this on a queryset (like using it in a annotate).

During my research I’ve found theses F(), ExpressionWrapper, SubQuery, annotate but I can’t figure out how to use them for my problem.

Thanks for reading :)

Advertisement

Answer

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:

JavaScript
Advertisement