0

开门见山:
型号:

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。我尽力找到答案,但无法谷歌搜索我的具体问题。

谢谢!

4

2 回答 2

1

你的意思是:

products = ProductShop.objects.filter(
   shop__in=Shop.objects.filter()).annotate(Min(price)).order_by('price')

{% for ps in productshop %}
    Shop: {{ ps.product.shop }}
    Product: {{ ps.product }}
    Minimum Price: {{ ps.price }}
{% endfor %}
于 2013-03-10T11:47:45.347 回答
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这里)

于 2013-05-06T08:30:55.770 回答