Django query annotation with boolean field

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

    Read the docs about extra

    qs = Product.objects.extra(select={'has_images': 'CASE WHEN images IS NOT NULL THEN 1 ELSE 0 END' })
    

    Tested it works

    But order_by or where(filter) by this field doesn't for me (Django 1.8) 0o:

    If you need to order the resulting queryset using some of the new fields or tables you have included via extra() use the order_by parameter to extra() and pass in a sequence of strings. These strings should either be model fields (as in the normal order_by() method on querysets), of the form table_name.column_name or an alias for a column that you specified in the select parameter to extra().

    qs = qs.extra(order_by = ['-has_images'])
    
    qs = qs.extra(where = ['has_images=1'])
    

    FieldError: Cannot resolve keyword 'has_images' into field.

    I have found https://code.djangoproject.com/ticket/19434 still opened.

    So if you have such troubles like me, you can use raw

提交回复
热议问题