我定义了以下三个表。
class Operator(models.Model):
DisplayName = models.CharField(max_length=64)
class Meta:
app_label = "Experiment"
db_table = "EXPERIMENT_OPERATOR"
class OperatorSummary(models.Model):
Operator = models.ForeignKey(Operator, related_name="TransactionSummary")
TransactionCount = models.IntegerField()
TransactionValue = models.DecimalField(max_digits=18, decimal_places=2)
StartTime = models.DateTimeField(default=timezone.now())
class Meta:
app_label = "Experiment"
db_table = "EXPERIMENT_OPERATORSUMMARY"
class OperatorAlerts(models.Model):
Operator = models.ForeignKey(Operator, related_name="AlertSummary")
AlertScore = models.IntegerField()
AlertCount = models.IntegerField()
StartTime = models.DateTimeField(default=timezone.now())
class Meta:
app_label = "Experiment"
db_table = "EXPERIMENT_OPERATORALERTS"
对于Operator
,我想检索给定日期范围的AlertScore
和。TransactionCount
我正在使用的查询如下所示:
tz = timezone.get_default_timezone()
vs = Operator.objects.filter(DisplayName="Jimmy",
TransactionSummary__StartTime__gte=tz.localize(datetime(year=2013, month=10, day=1)),
AlertSummary__StartTime__gte=tz.localize(datetime(year=2013, month=10, day=1)))\
.annotate(TotalTransactions=Sum("TransactionSummary__TransactionCount"),
TotalAlerts=Sum("AlertSummary__AlertScore"))\
.values("DisplayName", "TransactionSummary__TransactionCount", "AlertSummary__AlertScore")
此查询执行笛卡尔积并返回OperatorAlerts
和OperatorSummary
表中与查询匹配的所有行。这是它返回的内容:
{'AlertSummary__AlertScore': 20, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 10}
{'AlertSummary__AlertScore': 44, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 10}
{'AlertSummary__AlertScore': 543, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 10}
{'AlertSummary__AlertScore': 20, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 22}
{'AlertSummary__AlertScore': 44, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 22}
{'AlertSummary__AlertScore': 543, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 22}
{'AlertSummary__AlertScore': 20, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 234}
{'AlertSummary__AlertScore': 44, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 234}
{'AlertSummary__AlertScore': 543, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 234}
我想解决这个问题,以便得到以下结果:
{'AlertSummary__AlertScore': 607, 'DisplayName': u'Jimmy', 'TransactionSummary__TransactionCount': 266}
所有结果都折叠成一行,其中AlertScore
和TransactionCount
相加。
那可能吗?我总是可以回退到对 进行单独查询,OperatorAlerts
然后OperatorSummary
在 Python 中迭代结果集以获得我想要或调用的结果.aggregate
,但我确定一定有更好的方法吗?