B
B
bQ12019-08-05 09:28:48
Django
bQ1, 2019-08-05 09:28:48

How to sort QuerySet by method?

There are two tables:
1) Users
2) Posts
Linked by ForeignKey
There is a method:
def get_posts_count(self):
return self.get_posts().count()
How to sort the queryset by this method? and is it even possible?
Tried like this: users.order_by('get_posts_count') - Cannot resolve keyword

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Sviridov, 2019-08-05
@bQ1

The easiest way is not to count the number for each user every time, but when a user creates / deletes his record, count the number of his records once and update its value in the field in the user table. That is, in the table with users you will have a field posts_count, which will store the number of posts of the user) - and just sort by it. This is both easier and faster.
And if you do it through the get_posts_count method, then to display a list of users with the number of their posts on the page, you will make N requests to the database to count the number, where N is the number of users that will be displayed on the page, which is not at all optimal.
But if you really want not to make a separate field and count the number in one request along with a selection of users, then you can use annotate (taken from the docks):

>>> from django.db.models import Count
>>> q = Book.objects.annotate(Count('authors'))
# Interrogate the first object in the queryset
>>> q[0]
<Book: The Definitive Guide to Django>
>>> q[0].authors__count
2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question