Python 如何以最低价格获得外物
我有两门课Python 如何以最低价格获得外物,python,django,django-queryset,Python,Django,Django Queryset,我有两门课产品和优惠 class Product: ... name = models.CharField(max_length=255) ... class Offer: ... price = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) ... 我必须在一个queryset中以最低的价格获得产品的报价。我知道
产品
和优惠
class Product:
...
name = models.CharField(max_length=255)
...
class Offer:
...
price = models.IntegerField()
product = models.ForeignKey(Product, on_delete=models.CASCADE)
...
我必须在一个queryset中以最低的价格获得产品的报价。我知道我可以得到这样的价格:
Product.objects.filter(...).annotate(minimal_price=Min('offer__price').values('minimal_price', ...)
Product.objects.filter(...).annotate(offer_with_minimal_price=Min('offer__price__but_return_offer_not_price').values('offer_with_minimal_price', ...)
或
但我必须在单一查询中获得以下产品的报价:
Product.objects.filter(...).annotate(minimal_price=Min('offer__price').values('minimal_price', ...)
Product.objects.filter(...).annotate(offer_with_minimal_price=Min('offer__price__but_return_offer_not_price').values('offer_with_minimal_price', ...)
您可以从查询中获取第一个对象
Product.objects.filter(…).values('price')。annotate(Min('price'))。order_by('price')[0]
我还没检查过,但应该可以用
你也可以使用
Product.objects.filter(…).annotation(offer\u with_minimal\u price=Min('offer\u price\u但返回\u offer\u not_price')。value('offer\u with_minimal\u price','id',…)。get(id=id)
获取报价