Django query annotation with boolean field

前端 未结 6 1144
庸人自扰
庸人自扰 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:57


    I eventually found a way to do this using django 1.8's new conditional expressions:

    from django.db.models import Case, When, Value, IntegerField
    q = (
        Product.objects
               .filter(...)
               .annotate(image_count=Count('images'))
               .annotate(
                   have_images=Case(
                       When(image_count__gt=0,
                            then=Value(1)),
                       default=Value(0),
                       output_field=IntegerField()))
               .order_by('-have_images')
    )
    

    And that's how I finally found incentive to upgrade to 1.8 from 1.7.

提交回复
热议问题