Get latest entries from two other tables per record
I have these three classes:
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)
What I want to do is get all vehicles with their latest mileage and price from the respective classes, and all this in one query. Currently I'm getting all three separately, then inserting what I want into a dictionary item for template use, like this:
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)
Is there a better way I can retrieve what I want and have the least amount of queries running? Currently the above code needs abo开发者_开发知识库ut 100 queries.
There is something called reverse relationship in django orm. You can use the lowercase name of the of the model in this case vehiclemileage
and vehicleprice
with the Vehicle
model to get the result set.
This is how the query looks:
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')
This should return latest vehicles with its relevant price and mileage resulting in one query and returning one dataset.
sorry but you'll have to scroll to see the entire query.
精彩评论