2010-06-09 41 views
0

模型的Django聚集:使用對象

class Product(models.Model): 
    name = models.CharField(max_length = 128) 
    (...)  
    def __unicode__(self): 
    return self.name 

class Receipt(models.Model): 
    name = models.CharField(max_length=128) 
    (...) 
    components = models.ManyToManyField(Product, through='ReceiptComponent') 

    def __unicode__(self): 
    return self.name 

class ReceiptComponent(models.Model): 
    product = models.ForeignKey(Product) 
    receipt = models.ForeignKey(Receipt) 
    quantity = models.FloatField(max_length=9) 
    unit = models.ForeignKey(Unit) 
    def __unicode__(self): 
    return unicode(self.quantity!=0 and self.quantity or '') + ' ' + unicode(self.unit) + ' ' + self.product.genitive 

現在我想獲得最經常有用產品的名單:

ReceiptComponent.objects.values('product').annotate(Count('product')).order_by('-product__count' 

的例子結果:

[{'product': 3, 'product__count': 5}, {'product': 6, 'product__count': 4}, {'product': 5, 'product__count': 3}, {'product': 7, 'product__count': 2}, {'product': 1, 'product__count': 2}, {'product': 11, 'product__count': 1}, {'product': 8, 'product__count': 1}, {'product': 4, 'product__count': 1}, {'product': 9, 'product__count': 1}] 

這幾乎是我需要的。但我寧願讓Product對象不具有產品價值,因爲我想在views.py中使用它來生成列表。

回答

0

如果我沒有弄錯,這有同樣的行爲,但與對象?

Product.objects.all().annotate(usecount=Count('receipt_set')).order_by('-usecount') 
+0

好吧。我不知道爲什麼 - 但是你是對的; D(小錯誤 - 不是收據集,而是收據或收據組件)不要問我是哪個 - 因爲兩者都返回相同的結果; D – 2010-06-09 11:43:15

+0

我很困惑,爲什麼它有效 - dunno Django比我更聰明 – 2010-06-09 11:52:51

+0

它並不複雜,你實際上想要得到一個產品的使用次數,大多數人會邏輯地假設:我會檢查所有的收據和產品數量,給我這個數字。 ,反過來說,計算產品的每個recepit都給出了完全相同的結果:p,這就是我在這裏使用的;-)。 – KillianDS 2010-06-09 18:37:54