2016-11-04 28 views
0

當前狀態:複雜的註解

model.py

class Foo(models.model): 
    name = models.CharField(max_length = 50, blank = True, unique = True) 

class Item(models.model): 
    foo = models.ForeignKey('Foo') 
    number = models.PositiveIntegerField() 

views.py

def index(request): 
    stats= Foo.objects.filter(somecond=somevalue).\ 
    annotate(count=Count('item__number'), max=Max('item__number')) 

    return render_to_response('stats.html', {'stats' : stats}) 

和預期的結果是一個額外的字段對象富的列表:包含與Foo相關的項目的計數和max - 項目的最大數目。

例如:

Item1: Foo1, 12 
Item2: Foo2, 100 
Item3: Foo1, 10 
Item4: Foo2, 78 
Item5: Foo1, 6 

結果:

統計:

Foo1, 3, 12 
Foo2, 2, 100 

奧萊特。 現在我想獲得更多的:

class sell(models.Model): 
    foo = models.ForeignKey('Foo') 
    value = models.DecimalField(max_digits=10,decimal_places=2) 

填充:

sell1: Foo1, 12.50 
sell2: Foo2, 12.40 
sell3: Foo1, 4.12 
sell4: Foo2, 10.00 



stats=Foo.objects.filter(somecond=somevalue).\ 
annotate(Count('item__number'), Max('item__number'), Sum('sell__value')) 

我的期望是:

統計:

Foo1, 3, 12, 16.62 
Foo2, 2, 100, 22.40 

但結果是某種物品和價值數量的乘積(例如,如果銷售要素是一個,並且有四個Foos,則s嗯是4 * sell.value)

我也試過Sum('sell__value',distinct = True),但沒有區別。

我想它的模板,在這裏我要爲循環與統計

{% for foo in stats %} 
<h2>{{ foo.name }} </h2> 
{{foo.count}}/{{foo.max}} 
sum of sell related with foo 
{{foo.sum}} 

這是辦法,我想插入和存入統計做。

回答

0

我選擇的解決方案

stats=Foo.objects.filter(somecond=somevalue).annotate(Count('item__number'), Max('item__number')).in_bulk() 
sells=Foo.objects.filter(somecond=somevalue).annotate(Sum('sell__value')).in_bulk() 
for key, stat in stats.items(): 
    setattr(stat,'sell__value__sum',sells[key].sell__value__sum) 

我知道in_bulk()調用兩個sqls,但這不是問題fo我。我的其他答案調用一個SQL。