优化外键& REST API查询中的manytomany字段

时间:2017-12-22 08:10:27

标签: rest api django-rest-framework

我想知道在使用外键和ManytoMany字段时是否有优化api,例如:

Serializer:

class SerializerA(serializers.ModelSerializer):
    class Meta:
        model = Model_A
        fields = ('id', 'official_name', 'gender')
        depth = 1

class SerializerB(serializers.ModelSerializer):
    user = SerializerA(many=True)
    class Meta:
        model = Model_B
        fields = ('id', 'project_name','project_type', 'project_start_date', 'user')
        depth = 1

API:

class ReportAPI(APIView):
    def get(self, request):
        all_projects = Model_B.objects.all()
        project_serializer = SerializerB(all_projects, many=True)
        return Response(project_serializer.data)

现在有了这个,如果我转到API网址,并调试此页面,它会显示我正在从SQL查询中查询78次。但是,如果我从manytoMany seriealizer字段中移除一个字段'gender',页面现在只会从数据库中查询21次,那么我的问题又是如何,我该如何优化呢?

1 个答案:

答案 0 :(得分:1)

您可以使用select_related(对于ForeignKey)和/或prefetch_related(对于ManyToMany或ManyToOne),以便它不会为每个Model_B对象访问数据库。

如果userModel_B中的FK,那么您可以执行以下操作:

class ReportAPI(APIView):
    def get(self, request):
        all_projects = Model_B.objects.all().select_related('user')
        project_serializer = SerializerB(all_projects, many=True)
        return Response(project_serializer.data)

如果用户模型在其序列化程序中包含您需要的其他FK,那么您也可以执行select_related('user', 'user__other_field')