我试图过滤我的一个Django模型中出现最多的元素(在本例中,是销售额最高的用户),然后对其进行排序。经过一番挖掘,我得出了以下解决方案:
best_seller = [seller for seller in Sale.objects.values_list("seller", flat=True).annotate(s_count=Count("seller")).order_by("-s_count")]
seller 是我的里面的一列 Sale 包含User对象的表。给定的代码只返回一个数组,该数组包含(可能是?)找到的用户的ID/ID,而不是查询集本身。
seller
Sale
只需使用查询集:
Seller.objects.annotate(s_count=Count('sale_set')).order_by('-s_count')
这将返回 Seller s按数量排序 相关的 Sale s
Seller