在Django查询中排除注解项的计数
我正在查询数据库,想要获取一个对象的列表,并使用annotate()来统计每个对象关联的项目数量。
我希望只返回那些关联的item
数量超过5的对象。
lists = List.objects.exclude(picture_url='').exclude(picture_url__icontains='google').select_related('city','city__country', 'user', 'user__profile').annotate(items_added=Count('item'))[:10]
1 个回答
4
lists = List.objects.exclude(picture_url='') \ .exclude(picture_url__icontains='google') \ .select_related('city','city__country', 'user', 'user__profile') \ .annotate(items_added=Count('item')) \ .filter(items_added__gt=5)[:10]
跟aggregate()不一样,annotate()不是一个终结的操作。使用annotate()后,你得到的是一个查询集(QuerySet);这个查询集可以通过其他任何查询集的操作来修改,比如filter()、order_by,甚至可以再调用一次annotate()。