Django:如何在prefetch_related内部进行注释

时间:2019-03-10 19:53:13

标签: django django-orm

我仍在优化Django查询,并在prefetch_related函数中的注释方面苦苦挣扎。

型号:

class Car(models.Model):
    title = models.CharField(max_length=255)

class RepeatServiceType(models.Model):
    title = models.CharField(max_length=255)
    cars = models.ManyToManyField(Car)

class RepeatService(models.Model):
    service_type = models.ForeignKey(RepeatServiceType)
    car = models.ForeignKey(Car)
    mileage = models.BigIntegerField(default=0)

查看:

cars = Car.objects.all().prefetch_related('repeatservicetype_set')
for car in cars:
    services_types = car.repeatservicetype_set.all()\
    .annotate(service_mileage=Max('repeatservice__mileage', filter=Q(repeatservice__car=car)))
    #this hit DB query for each car iteration!
    print(services_types.service_mileage)

我已经尝试过预取类似的东西,但是没有运气:

prefetch_related(Prefetch('repeatservicetypes', queryset=Subquery(RepeatServiceType.objects.annotate(service_mileage=Max('repeatservice__mileage', filter=Q(repeatservice__car__pk=OuterRef('pk')))))))

如何在prefetch_related函数内部进行注释?

Django 2.0,可以根据需要升级到2.1。

谢谢!

0 个答案:

没有答案