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'>

ただし、上記の行は Location オブジェクトではなく int を返します。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 のORDER OF annotate() AND filter() CLAUSESにも注意してください。

于 2011-03-10T17:57:23.933 に答える