您实际上可以通过子类化一些聚合功能来做到这一点。MAX
这需要深入研究代码才能真正理解,但这是我编写的代码来为and做类似的事情MIN
。(注意:此代码基于 Django 1.4 / MySQL)。
首先继承底层聚合类并覆盖 as_sql 方法。此方法将实际 SQL 写入数据库查询。我们必须确保引用正确传入的字段并将其与正确的表名相关联。
from django.db.models.sql import aggregates
class SqlCalculatedSum(aggregates.Aggregate):
sql_function = 'SUM'
sql_template = '%(function)s(%(field)s - %(other_field)s)'
def as_sql(self, qn, connection):
# self.col is currently a tuple, where the first item is the table name and
# the second item is the primary column name. Assuming our calculation is
# on two fields in the same table, we can use that to our advantage. qn is
# underlying DB quoting object and quotes things appropriately. The column
# entry in the self.extra var is the actual database column name for the
# secondary column.
self.extra['other_field'] = '.'.join(
[qn(c) for c in (self.col[0], self.extra['column'])])
return super(SqlCalculatedSum, self).as_sql(qn, connection)
接下来,子类化通用模型聚合类并覆盖 add_to_query 方法。此方法决定了如何将聚合添加到底层查询对象。我们希望能够传入字段名称(例如queue
)但获得相应的数据库列名称(以防它有所不同)。
from django.db import models
class CalculatedSum(models.Aggregate):
name = SqlCalculatedSum
def add_to_query(self, query, alias, col, source, is_summary):
# Utilize the fact that self.extra is set to all of the extra kwargs passed
# in on initialization. We want to get the corresponding database column
# name for whatever field we pass in to the "variable" kwarg.
self.extra['column'] = query.model._meta.get_field(
self.extra['variable']).db_column
query.aggregates[alias] = self.name(
col, source=source, is_summary=is_summary, **self.extra)
然后,您可以在这样的注释中使用您的新类:
queryset.annotate(calc_attempts=CalculatedSum('attempts', variable='queue'))
假设您的attempts
和queue
字段具有相同的 db 列名,这应该会生成类似于以下内容的 SQL:
SELECT SUM(`LogQuarter`.`attempts` - `LogQuarter`.`queue`) AS calc_attempts
你去吧。