Skip to content
Advertisement

Sort a QuerySet by ManyToManyField in Django

I have a model like this:

class my_model(models.Model)
    foo = models.ManyToManyField(My_other_model)

I want to get all Objects of my_model sorted by the number of objects in the foo field. In this Question A friendly Guy from russia says, that you should use django-annontation. I tried the following:

my_model.objects.all().order_by("-foo")

and it works fine. Is there any reason I should go the longer way with annotations?? Thx for help and stay healthy!

Advertisement

Answer

From the docs, your use case is okay to use just .order_by(). For more complex queries you will use the .annotate() like so:

below_5 = Count('book', filter=Q(book__rating__lte=5))
pubs = Publisher.objects.annotate(below_5=below_5)

You can also make multiple annotations like so:

below_5 = Count('book', filter=Q(book__rating__lte=5))
above_5 = Count('book', filter=Q(book__rating__gte=5))
pubs = Publisher.objects.annotate(below_5=below_5).annotate(above_5=above_5)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement