Python Django过滤器模型一对多关系,价格差异最大

Python Django过滤器模型一对多关系,价格差异最大,python,django,django-models,django-queryset,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_pl

我有一个带有外键的产品模型,上面有一些价格,我真的很想列出“最好”的产品。。。怎么做

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


有人能帮忙吗?我希望这是有道理的;)

简单方法-使用预定义字段

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
         ...

您可以使用
StdDev
(标准偏差)聚合器,因此您的查询集可以如下所示:

ps = Product.objects.filter(price__gt=1).annotate(dev=StdDev("price__price"), min_price=Min("price__price")).order_by('-dev')[:6]
最佳报价为
ps[0]。最低价格


希望这有助于达成一致。这将是最简单的实现。请注意,这不能用于sqlite…更多关于您是否知道如何只获得最新价格最低的产品??)