Django:如何获取最新的相关对象

时间:2019-03-03 19:19:41

标签: django

我正在优化Django查询,并努力获取最后一个相关项目。

型号:

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', ]

查看:

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

如何在不对每辆车进行数据库查询的情况下为每辆车添加最后的技术检查注释?谢谢!

P.S。 prefetch_related('cartechnicalinspection_set')不起作用

1 个答案:

答案 0 :(得分:0)

因此,您需要date_to之前timezone.now()之前的所有汽车,而现在date_to用于这些汽车。

from django.db.models import Max

# Filter: cars with date_to less than timezone.now()
# Annotate: attach the greatest date_to as date_to to each car object.

cars = Car.objects.filter(cartechnicalinspection__date_to__lt=timezone.now()).annotate(date_to=Max('cartechnicalinspection__date_to'))

现在,如果您这样打印它们:

for car in cars:
    print(car.date_to)

对于每辆date_to少于date_to的汽车,您将获得timezone.now()