2014-01-26 17 views
6

我有一個產品模型,帶有一個外鍵給一些價格,我真的想列出產品的「最佳」報價...如何做那?Django濾波器模型一對多關係,價格差異最大

class Product(models.Model): 
    productname = models.CharField(max_length=1024) 

class Price(models.Model): 
    product = models.ForeignKey(Product) 
    price = models.DecimalField(max_digits=10, decimal_places=2) 
    created = models.DateTimeField(auto_now_add=True) 

首先我想所有的產品具有一個以上的代價,那我:

ps = Product.objects.annotate(c=Count("price")).filter(c__gt=2) 

現在我想最好的6種產品,這兩個最新的價格之間的差異最大。

任何人都可以幫忙嗎?我希望這是有道理的;)

回答

6

可以使用StdDev(標準差)聚合,所以你的查詢集可能看起來像這樣:

ps = Product.objects.filter(price__gt=1).annotate(dev=StdDev("price__price"), min_price=Min("price__price")).order_by('-dev')[:6] 

最好的報價價格是ps[0].min_price

希望這有助於

+0

請注意,這不能與sqlite一起使用...更多信息,請訪問https://docs.djangoproject.com/en/1.6/ref/models/querysets/#stddev – juliocesar

+0

你知道如何獲得產品嗎?最新的價格是最低的? ;) – pkdkk

4

簡單的辦法 - 使用預定義的領域

class Product(models.Model): 
    productname = models.CharField(max_length=1024) 
    price_diff = models.DecimalField(max_digits=10, decimal_places=2, default=0) 

使用信號或覆蓋保存和刪除:

class Price(models.Model): 
    product = models.ForeignKey(Product) 
    price = models.DecimalField(max_digits=10, decimal_places=2) 
    created = models.DateTimeField(auto_now_add=True) 
    def save(self, **kwargs): 
     ... 
     #calaculate you largest diff and put in product 
     ... 
+0

同意。這將是最簡單的實現。 – arocks