This post was exactly was I was looking for!
Just a reminder, don't forget to
from db.models import Count
On Jan 11, 8:51 pm, Margie Roginski wrote:
> Ah - yes, that is so awesome! For anyone interested, here's the magic
> incantation:
>
>
Ah - yes, that is so awesome! For anyone interested, here's the magic
incantation:
Book.objects.annotate(Count('reader')).order_by('reader__count')
Or more verbosely:
Book.objects.annotate(num_readers=Count('reader')).order_by
('num_readers')
That documentation link describes it very well.
Margie Roginski wrote:
Say I have a Reader model that has a foreign key to a Book
class Reader(models.Model):
book = models.ForeignKey(Book)
Now say I want to find all books and order them by the number of
readers. Is that possible, ie something like this?
Say I have a Reader model that has a foreign key to a Book
class Reader(models.Model):
book = models.ForeignKey(Book)
Now say I want to find all books and order them by the number of
readers. Is that possible, ie something like this?
Book.objects.all().order_by(reader_set__count)
This
4 matches
Mail list logo