【发布时间】:2015-09-19 01:40:59
【问题描述】:
假设我有一个 Product 模型,其中包含店面中的产品,以及一个带有产品图像的 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')
我该怎么做?谢谢!
【问题讨论】:
-
也许您只需要过滤而不是排序?这个简单的答案帮助我过滤:books.agiliq.com/projects/django-admin-cookbook/en/latest/…
标签: python django orm django-queryset