使用预取相关和模型资源进行Tastypie优化



我有以下ModelResource:

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查询,它不会在PlantsResource中执行prefetch_related和select_related。它为每个单独的工厂选择productionline_set和picture,而不是在SQL查询中执行。为什么?

然而,我发现我可以做这样的事情:

queryset = Division.objects.all().prefetch_related('plant_set', 'plant_set__picture','plant_set__productionline_set')

是否必须在分段模型中确定执行此操作?如果在从父级调用时不调用"prefetch"one_answers"select_related",则会超长。。

您可以使用扩展django-tastypie指定的字段(我是作者)。您指定要获取的字段,它将自动为您添加onlyselect_related

然而,它还不支持m2m关系和prefetch_related。尽管实现起来应该相当琐碎,尤其是对于一个深度级别而言。如果你想要,请告诉我,我会添加它。

最新更新