如何通过多方字段中的条目数对查询集结果进行排序?

时间:2019-07-26 18:07:17

标签: django django-queryset manytomanyfield

让我们说我有这个查询集:

                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)

我首先要显示在bookmarked_by字段中条目数量最多的对象。 有办法吗? 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

使用聚合函数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