darkhorse
darkhorse

Reputation: 8722

Order queryset using the number of related objects in Django

Let's say I have the following in models.py:

class A(models.Model):
    ...

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)

What I want to do is sort a queryset for A based on how many B objects they have, in descending order. What is the best approach to this issue? Thanks for any help.

Upvotes: 2

Views: 49

Answers (2)

Suling Jennifer
Suling Jennifer

Reputation: 21

This is:

queryset = A.objects.filter().order_by('B_A')

Here 'B_A' you have to put the related name

class A(models.Model):
    ...

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE, related_name = 'B_A')

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can work with a .annotate(…) [Django-doc] and then .order_by(…) [Django-doc]:

from django.db.models import Count

A.objects.annotate(
    nb=Count('b')
).order_by('-nb')

Since you can work with .alias(…) [Django-doc] to prevent calculating this both as column and in the ORDER BY clause:

from django.db.models import A

A.objects.alias(
    nb=Count('b')
).order_by('-nb')

Upvotes: 4

Related Questions