Django使用布尔字段查询注解 [英] Django query annotation with boolean field
问题描述
假设我有一个产品
模型,产品在店面,而 ProductImages
表与产品的图像,可以有零个或多个图像。这是一个简化的例子:
class Product(models.Model):
product_name = models.CharField(max_length = 255)
#...
class ProductImage(models.Model):
product = models.ForeignKey(Product,related_name ='images')
image_file = models.CharField(max_length = 255)
#...
当显示产品的搜索结果时,我想优先考虑具有与之相关的图像的产品。我可以轻松获取图像数量:
from django.db.models import Count
Product.objects.annotate(image_count = Count('images'))
但实际上我想要的是。我想使用布尔字段 have_images
来注释它,指示产品是否有一个或多个图像,以便我可以按以下顺序排序:
Product.objects.annotate(have_images =(?????))。order_by(' - have_images' 'product_name')
我该怎么做?谢谢!
我最终找到了一种使用django 1.8的新版本href =https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/ =noreferrer>条件表达式:
$ b $导入case,当,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')
)
这就是我终于找到激励从1.7升级到1.8的方式。
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 images. Here's a simplified example:
class Product(models.Model):
product_name = models.CharField(max_length=255)
# ...
class ProductImage(models.Model):
product = models.ForeignKey(Product, related_name='images')
image_file = models.CharField(max_length=255)
# ...
When displaying search results for products, I want to prioritize products which have images associated with them. I can easily get the number of images:
from django.db.models import Count
Product.objects.annotate(image_count=Count('images'))
But that's not actually what I want. I'd like to annotate it with a boolean field, have_images
, indicating whether the product has one or more images, so that I can sort by that:
Product.objects.annotate(have_images=(?????)).order_by('-have_images', 'product_name')
How can I do that? Thanks!
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.
这篇关于Django使用布尔字段查询注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!