Django Annoation:从注释值而不是 ID 获取对象
我是 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(需要单独的可能昂贵的查找)?
非常感谢任何建议。
谢谢, 乔
I'm new to Django Annotations and I'm trying to generate a summary report of Order income at given Locations.
For example, the report would look something like this:
Location Name | Location Type | Sum of Order Subtotal
And these are example models that I would use:
class Order(models.Model):
order_subtotal = models.DecimalField(...)
location = models.ForignKey('Location')
....
class Location(models.Model):
name = models.CharField(...)
type = models.IntegerField(...)
....
I'm able to run some queries to annotate...
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'>
However, the line above returns an int rather than a Location object. I'd like to be able to somehow reference the location name and location type like location.name or location.type. Is there some way to return a location object in the annotation rather than only the location id (requiring separate potentially expensive lookups)?
Any advice is much appreciated.
Thanks,
Joe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
计算每个位置的
order_subtotal
总和:计算每个位置类型的
order_subtotal
总和:计算每个位置的总和,但不包括超过 14 天的订单::
另外请注意: ORDER OF annotate() AND filter() 条款 在 django 文档中。
Calculate sum of
order_subtotal
for each location:Calculate sum of
order_subtotal
for each location type:Calculate sum for each location, but don't include orders older than 14 days::
Also give some attention to: ORDER OF annotate() AND filter() CLAUSES at django docs.