使用Django中ManyToMany模型的额外字段进行注释

时间:2013-03-10 11:42:40

标签: python django model many-to-many

直截了当:
模型:

class Shop(models.Model):
    name = models.CharField(max_length=255)        

class Product(models.Model):
    name = models.CharField(max_length=255)
    shops = models.ManyToManyField(Shop, through='ProductShop', related_name='products')

class ProductShop(models.Model):
    product = models.ForeignKey(Product)
    shop = models.ForeignKey(Shop)
    price = models.DecimalField(max_digits=20, decimal_places=2)

现在,我希望获得所有销售此产品的商店中以最低价格订购的产品列表。我总是使用annotate来进行此类查询,但在这里我无法想到任何解决方案。这大致是我想要的:

products = Product.objects.annotate(price=SOMETHING_TO_GET_THE_LOWEST_PRICE_PER_PRODUCT).order_by('price')

有什么好的解决方案吗?我知道extra,但不想写简单的SQL。我尽力找到答案,但无法解决我的具体问题。

谢谢!

1 个答案:

答案 0 :(得分:0)

最后解决了一个小问题:

class Product(models.Model):
    name = models.CharField(max_length=255)
    shops = models.ManyToManyField(Shop, through='ProductShop', related_name='products')
    def lowest_possible_price(self):
        shops = self.shops.all()
        if not shops:
            return "N/A"
        return reduce(lambda x, y: min(x, ProductShop.objects.get(shop__pk=y.id, product__pk=self.id).price), 
                shops, ProductShop.objects.get(shop__pk=shops[0].id, product__pk=self.id).price)


products = sorted(Product.objects.all(),
        key = lambda product : product.lowest_possible_price())

如果有一个没有辅助函数的单行解决方案(lowest_possible_price这里),仍然困扰我