Order queryset using the number of related objects in Django

Viewed 33

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.

2 Answers

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')
Related