【发布时间】:2012-02-09 07:46:52
【问题描述】:
我有一个对象:
class Image(models.Model):
width = models.IntegerField(...)
height = models.IntegerField(...)
class Foo(models.Model):
title = ...
image = models.ForeignKey(Image ...)
我想尝试检索所有具有相似纵横比的相关图像的Foo 对象。在一个完美的世界中,类似于:
ratio = width/height
min = ratio - 0.25
max = ratio + 0.25
similar = ImageMeta.objects \
.annotate(ratio=Div('image__width', 'image__height')\
.filter(ratio__gte=min).filter(ratio__lte=max)
但是没有这样的divison聚合函数。 This answer 建议使用extra,即
.extra({ 'select' : 'width/height' )
但由于宽度和高度在不同的表中,我不确定如何跨越关系(即编写 SQL)来执行此操作。有人可以提供一些帮助吗?
【问题讨论】:
标签: sql django aggregate-functions