在嵌套序列化程序中使用selected_related()

时间:2019-04-10 19:15:15

标签: django django-rest-framework

我一直在使用select_related()来加快大型DRF通话的速度,但是非常成功,但是我遇到了麻烦。

我的主串行器引用了另外两个串行器,其中一个引用了另一个串行器。我不确定如何在第二级序列化程序中实现预取。

serializer.py

class DocumentsThinSerializer(serializers.ModelSerializer):
    class Meta:
        model = Documents
        fields = ('confirmed', )


class PersonThinSerializer(serializers.ModelSerializer):
    documents = DocumentsThinSerializer()

    class Meta:
        model = Person
        fields = ('name', 'age', 'gender')


class EventThinSerializer(serializers.ModelSerializer):

    day = DayThinSerializer()
    person = PersonThinSerializer()

    @staticmethod
    def setup_eager_loading(queryset):
        return queryset.select_related('day', 'person')

    class Meta:
        model = Event

views.py


class EventList(generics.ListAPIView):
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)
    queryset = Event.objects.all()
    serializer_class = EventThinSerializer

    def get_queryset(self):
        return self.get_serializer_class().setup_eager_loading(queryset)

如您所见,我正在使用静态方法setup_eager_loading()来使事情顺利进行,但是我找不到PersonThinSerializer()的queryset挂钩来获取访问{{ 1}}。

1 个答案:

答案 0 :(得分:1)

假设Documents具有Person的外键,则应该可以将"person__documents"添加到queryset.select_related中的EventThinSerializer.setup_eager_loading中:

class EventThinSerializer(serializers.ModelSerializer):

    day = DayThinSerializer()
    person = PersonThinSerializer()

    @staticmethod
    def setup_eager_loading(queryset):
        return queryset.select_related('day', 'person', 'person__documents')