【问题标题】:Django Annoation: Getting Object from Annoation Values Rather than IDDjango Annotate:从注释值而不是 ID 中获取对象
【发布时间】:2011-03-10 17:07:22
【问题描述】:

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

非常感谢任何建议。

谢谢, 乔

【问题讨论】:

    标签: django annotations models summary


    【解决方案1】:

    计算每个位置的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'))
    

    还要注意:ORDER OF annotate() AND filter() CLAUSES at django docs。

    【讨论】:

    • 一个相关问题。有没有办法对作为注释的一部分求和的订单进行过滤?我知道我的示例没有那么详细,但想知道是否有办法过滤订单日期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多