我有这三个类:
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6)
vin = models.CharField(max_length=17)
year = models.ForeignKey(Year)
... (several other fields declared here)
class VehicleMileage(models.Model):
vehicle = models.ForeignKey(Vehicle)
odometer_reading = models.PositiveIntegerField()
date_time_added = models.DateTimeField(default=datetime.today, editable=False)
class VehicleMileage(models.Model):
vehicle = models.ForeignKey(Vehicle)
price = models.PositiveIntegerField()
date_time_added = models.DateTimeField(default=datetime.today, editable=False)
我想要做的是从所有类别中获取所有车辆的最新里程和价格,以及所有这些在一个查询中。目前我正在分别获取所有这三个,然后将我想要的内容插入到字典项中以供模板使用,如下所示:
vehicle_list = Vehicle.objects.all().values('vin', 'stock_number', 'year__year')
vehicles = []
for vehicle in vehicle_list:
lst = {}
latest_mileage = VehicleMileage.objects.filter(vehicle__stock_number =
stock_number).values('odometer_reading').order_by(
'-date_time_added')[0]
latest_price = VehiclePrice.objects.filter(vehicle__stock_number =
stock_number).values('price').order_by(
'-date_time_added')[0]
lst['stock_number'] = vehicle['stock_number']
lst['year'] = vehicle['year__year']
lst['vin'] = vehicle['vin']
lst['mileage'] = latest_mileage['odometer_reading']
lst['price'] = latest_price['price']
vehicles.append(lst)
有没有更好的方法可以检索我想要的内容并运行最少量的查询?目前上述代码需要大约100个查询。
答案 0 :(得分:2)
django orm中有一些名为reverse relationship的东西。您可以在此案例vehiclemileage
中使用模型的小写名称,并使用vehicleprice
模型使用Vehicle
来获取结果集。
这是查询的外观:
vehicles_with_latest_mileage_price = Vehicle.objects.values('vehiclemileage__odometer_reading','vehicleprice__price','vin','stock_number','year__year').order_by('-vehiclemileage__date_time_added','-vehicleprice__date_time_added')
这应该返回具有相关价格和里程数的最新车辆,从而导致一个查询并返回一个数据集。
抱歉,您必须滚动查看整个查询。