我是 Django Annotations 的新手,我正在尝试生成给定位置的订单收入摘要报告。
例如,报告将如下所示:
Location Name | Location Type | Sum of Order Subtotal
这些是我将使用的示例模型:
class Order(models.Model):
order_subtotal = models.DecimalField(...)
location = models.ForignKey('Location')
....
class Location(models.Model):
name = models.CharField(...)
type = models.IntegerField(...)
....
我可以运行一些查询来注释...
from django.db import models
In [1]: order_locations =\
Order.objects.values('location').annotate(models.Sum('order_subtotal'))
In [2]: order_locations[0]
Out[2]: {'location': 1, 'order_subtotal__sum': Decimal('1768.08')}
In [3]: location = order_locations[0]['location']
In [4]: location
Out[4]: 1
In [5]: type(location)
Out[5]: <type 'int'>
但是,上面的行返回一个 int 而不是 Location 对象。我希望能够以某种方式引用位置名称和位置类型,例如 location.name 或 location.type。有没有办法在注释中返回位置对象,而不仅仅是位置 ID(需要单独的可能昂贵的查找)?
非常感谢任何建议。
谢谢,乔