Farhani Walid
Farhani Walid

Reputation: 938

How to order a queryset result by the number of entries in a manytomanyfield?

Let's say that i have this queryset :

                result_list = []
                get_result_list = [x for x in search_text_imported.split() if len(x) > 2]
                for keyword in get_result_list:
                    result_list += list(Node.objects.filter((Q(name__icontains=keyword) | Q(Tags__icontains=keyword)), tree_type='root', tunisia_office=True, published=True ).order_by('-bookmarked_by'))
                    result = list(OrderedDict.fromkeys(result_list))

models.py

class Node(MPTTModel):
name                = models.TextField(blank=True, null=True)
bookmarked_by        = models.ManyToManyField(CustomUser, null=True, blank=True)

I want to show first the objects that have the most number of entries in the bookmarked_by field. Is there a way to do it ? Any help is appreciated.

Upvotes: 0

Views: 37

Answers (1)

Håken Lid
Håken Lid

Reputation: 23064

Use the aggregate function Count

from django.db.models import Count
Node.objects.annotate(
    num_bookmarks=Count('bookmarked_by')
).order_by('-num_bookmarks')

https://docs.djangoproject.com/en/2.2/topics/db/aggregation/#aggregation

Upvotes: 2

Related Questions