Django query annotation with boolean field

前端 未结 6 1146
庸人自扰
庸人自扰 2021-01-31 08:37

Let\'s say I have a Product model with products in a storefront, and a ProductImages table with images of the product, which can have zero or more im

6条回答
  •  太阳男子
    2021-01-31 08:48

    When you have to annotate existence with some filters, Sum annotation can be used. For example, following annotates if there are any GIFs in images:

    Product.objects.filter(
    ).annotate(
        animated_images=Sum(
            Case(
                 When(images__image_file__endswith='gif', then=Value(1)),
                 default=Value(0),
                 output_field=IntegerField()
            )
        )
    )
    

    This will actually count them, but any pythonic if product.animated_images: will work same as it was boolean.

提交回复
热议问题