Django 1.11中的条件表达式

时间:2018-04-24 17:51:00

标签: python django postgresql orm

我有3个型号:Product, Brand, Shop。我想在给定的Products中计算Brands可用的Shop 例如:
Adidas 50
Puma 25

 现在我有:

queryset = Brand.objects
            .filter(brand_id__in=id_list)
            .order_by('brand_name')

queryset =  queryset.annotate(amount_of_products=Count('products'))

但这给了我一些所有商店的产品。

我试过像here

queryset = queryset.annotate(
            amount_of_products=Count(
                Case(When(shops__shop_name__in=[shop], then=1))
            ))

但我为列表中的每个amount_of_products = 1获得Brand 有没有办法在Django 1.11中执行此条件表达式?

1 个答案:

答案 0 :(得分:0)

实际上设法修复了这个:)

queryset = queryset.annotate(
            amount_of_products=Count(
                Case(When(products__shop__shop_name__in=[shop], then=1))
            ))

这只是ForeignKey使用不当。

相关问题