我认为这不应该很复杂,但是我做不到。
如何有条件地计算查询集中特定类别中的品牌数量?
views.py
def get_brands(request):
all_brands = brand.objects.values('brand_name','brand_category').\
annotate(brand_proportion=Count('brand_name')/Count('brand_name',
filter=Q(brand_category="brand_category"))#I'm stuck here
return JsonResponse(list(all_brands), safe=False)
我不确定要筛选品牌类别并计算其中的品牌数量 类别。
For example:
brand_category 'A' might have: Brand 1,Brand 1 ,Brand 1,Brand 2,Brand 2
Here, the proportion of Brand 1 in category A would be 3/5 = 0.6 or 60%
I can calculate the 3 using Count('brand_name') within the queryset, but how can i calculate
the 5?
brand_category 'B' might have: Brand 1,Brand 2,Brand 3,Brand 4,Brand 5
Here, the proportion of Brand 1 in category B would be 1/5 = 0.2 or 20%
答案 0 :(得分:0)
关于django doc。
from django.db.models import Count
q = Book.objects.annotate(num_authors=Count('authors'))
total_authors = som([x.num_authors for x in q])
所以我希望我成功了。