Sql 在两个字段(跨越FK关系)的划分上创建查询

Sql 在两个字段(跨越FK关系)的划分上创建查询,sql,django,aggregate-functions,Sql,Django,Aggregate Functions,我有一个目标: class Image(models.Model): width = models.IntegerField(...) height = models.IntegerField(...) class Foo(models.Model): title = ... image = models.ForeignKey(Image ...) 我想尝试检索所有具有相似纵横比的相关图像的Foo对象。在一个完美的世界中,类似于: ratio = width/

我有一个目标:

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)
但是没有这样的除数聚合函数。建议使用
额外的
,即

.extra({ 'select' : 'width/height' )
但是因为宽度和高度在不同的表中,所以我不确定如何跨越关系(即编写SQL)来实现这一点。有人能帮忙吗

考虑使用而不是聚合

此查询乘以比率,在单个字段上进行直接比较:

Foo.objects.filter(image__width__gte=F('image__height') * min_ratio, 
                   image__width__lte=F('image__height') * max_ratio)