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
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,)