2016-11-02 10 views
0

で集計を取得します。私の見解では私はこのDjangoのモデル持っているテンプレート

class Location(models.Model): 
    name = models.CharField(primary_key=True, max_length=100) 
    customer = models.OneToOneField(Customer, default=None) 

class Customer(models.Model): 
    name = models.CharField(primary_key=True, max_length=100) 

class Order(models.Model): 
    amount = models.PositiveIntegerField(default=0) 
    customer = models.ForeignKey(Customer, default=0) 

を、私はこのようにそれらを取得する:

locations = models.Location.objects.all() 

とテンプレートは、このようにそれらを示しています。

{% for location in locations %} 
    {{ location.customer.name }} 
{% endfor %} 

Orderのすべてのamountの合計をその顧客と結びつけたいと思います以下のようなmething:

{% for location in locations %} 
    {{ location.customer.name }} ordered {{ location.customer.orders.sum(amount) }} items 
{% endfor %} 

そしてthis questionによると、私は、ビューでそれを行う必要がありますが、どのように?

+0

[aggregation docs](https://docs.djangoproject.com/en/1.10/topics/db/aggregation/)に従ってください。正確にどこに問題がありますか? –

+0

@DanielRoseman私は何を試して質問を更新しましたが、問題は別のモデル(前に間違ったモデルを投稿しました)があります。 –

答えて

1

あなたは.annotatelook in docs)を使用する必要があります:私はこの作品見つかったいくつかの周りfolling後

{% for customer in customers %} 
    {{ customer.name }} ordered {{ customer.orders_count }} items 
{% endfor %} 
+0

私はそれを働かせました。 'order'sをフィルタリングする方法はありますか? –

+0

@BartFriederichsはあなたが欲しいものの例を挙げてください – devxplorer

+0

私は特定の状態を持つ注文を数えたいだけです。 –

0

locations = models.Location.objects.annotate(num_order=Count('customer__order')) 

from django.db.models import Count 

customers = models.Customer.objects.annotate(orders_count=Count('order')) 

次にテンプレートで、あなたはこのようにそれを使用することができます

このテンプレートでこれを使用してください:

{% for location in locations %} 
    {{ location.customer.name }} ordered {{ location.num_order }} items 
{% endfor %} 
関連する問題