Reputation: 8722
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
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
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 django-3.2 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