Django REST Serializer doing N+1 database calls for multiple nested relationship, 3 levels

前端 未结 2 1234
离开以前
离开以前 2021-02-10 06:55

I have a situation where my model has a Foreign Key relationship:

# models.py
class Child(models.Model):
    parent = models.ForeignKey(Parent,)

class Parent(mo         


        
2条回答
  •  醉酒成梦
    2021-02-10 07:15

    As far as I remember, nested serializers have access to prefetched relations, just make sure you don't modify a queryset (i.e. use all()):

    class ParentSerializer(serializer.ModelSerializer):
        child = serializers.SerializerMethodField('get_children_ordered')
    
        def get_children_ordered(self, parent):
            # The all() call should hit the cache
            serialized_data = ChildSerializer(parent.child.all(), many=True, read_only=True, context=self.context)
            return serialized_data.data
    
        class Meta:
                model = Parent
    
    
    class ParentList(generics.ListAPIView):
    
        def get_queryset(self):
            children = Prefetch('child', queryset=Child.objects.select_related('parent'))
            queryset = Parent.objects.prefetch_related(children)
            return queryset
    
        serializer_class = ParentSerializer
        permission_classes = (permissions.IsAuthenticated,)             
    

提交回复
热议问题