Django过滤模型一对多关系,价格之间的最大差异

时间:2014-01-26 00:18:00

标签: python django django-models django-queryset

我有一个产品型号,带有一些价格的外键,我真的想列出具有“最佳”报价的产品......怎么做?

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种产品,两种最新价格之间的差异最大。

任何人都可以帮忙吗?我希望它有意义;)

2 个答案:

答案 0 :(得分: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

希望这有帮助

答案 1 :(得分: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
         ...