【问题标题】:Conditional Expression in Django 1.11Django 1.11 中的条件表达式
【发布时间】:2018-10-05 02:03:24
【问题描述】:

我有 3 个模型:Product, Brand, Shop。我想在给定的Shop 中计算Brands 可用的Products
例如:
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))
            ))

但是对于列表中的每个 Brand,我都会得到一个 amount_of_products = 1
有没有办法在 Django 1.11 中执行此条件表达式?

【问题讨论】:

    标签: python django postgresql orm


    【解决方案1】:

    实际上设法解决了这个问题:)

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

    ForeignKey 使用不当。

    【讨论】:

      猜你喜欢
      • 2016-07-08
      • 2016-11-09
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 2013-08-01
      • 1970-01-01
      相关资源
      最近更新 更多