假设我有这个查询集:
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字段中条目数最多的对象。有没有办法做到这一点?任何帮助,不胜感激。
使用聚合函数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