Python Django根据相关字段中的最新值查询订单
考虑Django中的以下模型:Python Django根据相关字段中的最新值查询订单,python,django,Python,Django,考虑Django中的以下模型: class Item(models.Model): name = models.CharField(max_length = 100) class Item_Price(models.Model): created_on = models.DateTimeField(default = timezone.now) item = models.ForeignKey('Item', related_name = 'prices') price = m
class Item(models.Model):
name = models.CharField(max_length = 100)
class Item_Price(models.Model):
created_on = models.DateTimeField(default = timezone.now)
item = models.ForeignKey('Item', related_name = 'prices')
price = models.DecimalField(decimal_places = 2, max_digits = 15)
一件商品的价格会随时间而变化,所以我想保留一个价格历史记录
我的目标是使用Django ORM进行一次查询,以获得具有最新价格的项目列表,并按此价格按升序对结果进行排序
实现这一点的最佳方法是什么?您可以预取它们,以便执行嵌套的内联排序,如下所示:
from django.db.models import Prefetch
prefetched_prices = Prefetch("prices", queryset=Item_Price.objects.order_by("price"))
for i in Item.objects.prefetch_related(prefetched_prices): i.name, i.prices.all()
您可以使用
子查询
获取最新的项目价格
对象并对其进行排序:
from django.db.models import OuterRef, Subquery
last_price = Item_Price.objects.filter(
item_id=OuterRef('pk')
).order_by('-created_on').values('price')[:1]
Item.objects.annotate(
last_price=Subquery(last_price)
).order_by('last_price')
从django.db.models导入OuterRef,子查询
上次价格=项目价格.objects.filter(
项目id=OuterRef('pk')
).order_by('-created_on')。value('price')[:1]
Item.objects.annotate(
上次价格=子查询(上次价格)
).订购人(“上次价格”)
因此,对于每个项目
,我们将获得最新的项目价格
,并在注释中使用
尽管如此,上述建模可能并不理想,因为它将需要大量复杂的查询。通过创建额外的模型和保存历史记录,可以实现不同的效果。它还有一个管理器,可以查询历史状态。这可能会使使用历史数据simpeler变得更方便。使用它可能会为历史记录构造一个额外的表,从而使查询“当前”状态更容易。