I'm working on optimization Django queries and struggling with getting the last related item.
Models:
class Car(models.Model):
title = models.CharField(max_length=255)
class CarTechnicalInspection(models.Model):
car = models.ForeignKey(Car)
date_to = models.DateField()
class Meta:
ordering = ['date_to', ]
View:
cars = Car.objects.all()
for car in cars:
ti = car.cartechnicalinspection_set.last() #hit DB query for each car iteration!
if ti and ti.date_to < timezone.now():
#do something
How to Annotate the last Technical Inspection for each car without a DB query for each car? Thanks!
P.S. prefetch_related('cartechnicalinspection_set') does not work