1

我是 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(需要单独的可能昂贵的查找)?

非常感谢任何建议。

谢谢,乔

4

1 回答 1

2

计算order_subtotal每个位置的总和:

>>> locations = Location.objects.all().annotate(total=Sum('order__order_subtotal'))
>>> [(loc.name, loc.typ, loc.total) for loc in locations]
[(u'A', 1, Decimal('10.00')),
 (u'B', 1, Decimal('20.00')),
 ...]

计算order_subtotal每种位置类型的总和:

>>> Location.objects.all().values('type').annotate(total=Sum('order__order_subtotal'))
[{'total': Decimal('70.00'), 'typ': 1}, {'total': Decimal('179.00'), 'typ': 2}]

计算每个位置的总和,但不包括超过 14 天的订单::

>>> starting_date = datetime.datetime.now() - datetime.timedelta(14)
>>> locations = Location.objects.filter(order__date_gte=starting_date) \
                                .annotate(total=Sum('order__order_subtotal'))

还要注意:django docs 上的annotate() AND filter() CLAUSES的顺序。

于 2011-03-10T17:57:23.933 回答