我有以下模型资源:
class DivisionsResource(ModelResource):
plants = fields.ToManyField('plants.api.resources.PlantsResource', 'plant_set', full = True)
class Meta:
queryset = Division.objects.all().prefetch_related('plant_set')
allowed_method = ['get']
filtering = {
"name": ('istartswith')
}
class PlantsResource(ModelResource):
picture = fields.ToOneField('files.api.resources.PlantPictureResource', 'picture', full=True)
production_lines = fields.ToManyField('production_lines.api.resources.ProductionLinesResource','productionline_set', full=True, null=True)
class Meta:
queryset = Plant.objects.select_related('picture').all().prefetch_related('productionline_set')
allowed_methods = ['get']
但是,如果我调用“divisions”资源并查看 SQL 查询,它不会执行Plants Resource中的 prefetch_related 和 select_related 。它会为每个单独的工厂选择生产线集和图片,而不是执行SQL查询。这是为什么?
但是我发现我可以做这样的事情:
queryset = Division.objects.all().prefetch_related('plant_set', 'plant_set__picture','plant_set__productionline_set')
我必须在Divisions Model中确定这样做吗?如果从父母调用时不调用“prefetch”和“select_related”,那将是超长的..