如何编写 Django 查询,其中 WHERE 条件的左侧是数学表达式?
How do I write a Django query where the left side of my WHERE condition is a math expression?
我正在使用 Django、Python 3.7 和 PostGres 9.5。我有一个包含以下字段的模型 ...
class DomainTrackerStat(models.Model):
domain = models.CharField(max_length=255)
...
num_negative_articles = models.IntegerField(default=0, null=False)
num_positive_articles = models.IntegerField(default=0, null=False)
我想写一个 Django 查询,说给我所有条件匹配这个 PostGres WHERE 子句的对象
WHERE num_negative_articles / (num_negative_articles + num_positive_articles) > .95
但是我在编写 Django 查询表达式时遇到了问题,因为通常它只允许一个字段,例如
DomainTrackerStat.objects.filter(num_negative_articles__gt=.95)
如何编写这个更复杂的查询?
您可以在查询集中注释数学表达式的值,然后按该注释值进行过滤:
DomainTrackerStat.objects.annotate(value=F('num_negative_articles') / (F('num_negative_articles ') + F('num_positive_articles'))).filter(value__gt=0.95)
F() 表达式可用于在模型字段之间执行算术运算(+、-、* 等),以定义它们之间的代数lookup/connection。
An F() object represents the value of a model field or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.
data = DomainTrackerStat.objects.annotate(result=F('num_negative_articles') / (F('num_negative_articles') + F('num_positive_articles'))).filter(result__gt=0.95)
现在数据中的每个项目都有一个名为 'result' 的额外列,其中包含 'num_positive_articles' 和 'num_negative_articles' 分别除以每个项目的 'num_negative_articles' 的乘积。
Documentation 进一步参考
我正在使用 Django、Python 3.7 和 PostGres 9.5。我有一个包含以下字段的模型 ...
class DomainTrackerStat(models.Model):
domain = models.CharField(max_length=255)
...
num_negative_articles = models.IntegerField(default=0, null=False)
num_positive_articles = models.IntegerField(default=0, null=False)
我想写一个 Django 查询,说给我所有条件匹配这个 PostGres WHERE 子句的对象
WHERE num_negative_articles / (num_negative_articles + num_positive_articles) > .95
但是我在编写 Django 查询表达式时遇到了问题,因为通常它只允许一个字段,例如
DomainTrackerStat.objects.filter(num_negative_articles__gt=.95)
如何编写这个更复杂的查询?
您可以在查询集中注释数学表达式的值,然后按该注释值进行过滤:
DomainTrackerStat.objects.annotate(value=F('num_negative_articles') / (F('num_negative_articles ') + F('num_positive_articles'))).filter(value__gt=0.95)
F() 表达式可用于在模型字段之间执行算术运算(+、-、* 等),以定义它们之间的代数lookup/connection。
An F() object represents the value of a model field or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.
data = DomainTrackerStat.objects.annotate(result=F('num_negative_articles') / (F('num_negative_articles') + F('num_positive_articles'))).filter(result__gt=0.95)
现在数据中的每个项目都有一个名为 'result' 的额外列,其中包含 'num_positive_articles' 和 'num_negative_articles' 分别除以每个项目的 'num_negative_articles' 的乘积。
Documentation 进一步参考