Python Django 1.11中的条件表达式
我有三种型号:Python Django 1.11中的条件表达式,python,django,postgresql,orm,Python,Django,Postgresql,Orm,我有三种型号:产品、品牌、商店。我想统计给定商店中品牌可用的产品 例如: 阿迪达斯50 Puma 25 现在我有: queryset = Brand.objects .filter(brand_id__in=id_list) .order_by('brand_name') queryset = queryset.annotate(amount_of_products=Count('products')) 但这给了我所有商店的产品数量。 我试过
产品、品牌、商店
。我想统计给定商店中品牌可用的产品
例如:
阿迪达斯50
Puma 25
现在我有:
queryset = Brand.objects
.filter(brand_id__in=id_list)
.order_by('brand_name')
queryset = queryset.annotate(amount_of_products=Count('products'))
但这给了我所有商店的产品数量。
我试过像:
但是对于列表中的每个品牌
,我得到的产品数量=1
。
有没有办法在Django 1.11中实现这个条件表达式?实际上已经解决了这个问题:)
那是不正确的ForeignKey
使用
queryset = queryset.annotate(
amount_of_products=Count(
Case(When(shops__shop_name__in=[shop], then=1))
))
queryset = queryset.annotate(
amount_of_products=Count(
Case(When(products__shop__shop_name__in=[shop], then=1))
))