Django query annotation with boolean field

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

    Use conditional expressions and cast outputfield to BooleanField

    Product.objects.annotate(image_count=Count('images')).annotate(has_image=Case(When(image_count=0, then=Value(False)), default=Value(True), output_field=BooleanField())).order_by('-has_image')
    

提交回复
热议问题