1

I have following Django Rest Framework Serializer:

from rest_framework.serializers import SerializerMethodField
from posts.api.serializers import CommentSerializer

class PostSerializer(ModelSerializer):
    comments = SerializerMethodField()
    
    class Meta:
        model = Post
        fields = ('id', 'title', 'comments')

    def get_comments(self, obj):
        return CommentSerializer(obj.comments.all(), many=True).data
            

And I have following View:

from rest_framework.views import APIView
from rest_framework.responses import Response
from posts.models import Post

class PostsAPIView(APIView):
    
    def get(request):
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data, status=200)

So, My question is, when my serializer is working to prepare JSON of posts, for getting comments of each post, it executes a database query or not?

For example, if I have 10 posts, is 11 database queries executed in this view? (1 query to get posts and 10 queries to get comments of each post in serializer).

msln
  • 1,318
  • 2
  • 19
  • 38

1 Answers1

2

Yes, it does execute the query inside your SerializerMethodField for each instance.

However, You make small modifications on your serializers and API, that will only call your database once.

  1. Don't use SerializerMethodField for related fields, instead, use the serializer itself. but it will still call your database for related data.
class PostSerializer(ModelSerializer):
    comments = CommentSerializer(many=True)
    
    class Meta:
        model = Post
        fields = ('id', 'title', 'comments')
  1. Use prefetch_related function to fetch all related data at once in your queryset:
class PostsAPIView(APIView):
    def get(request):
        # all .prefetch_related(...) after "all" or "filter"
        posts = Post.objects.all().prefetch_related('comments')
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data, status=200)

This way you are going to get all of your data at once, and your data will be serialized without the need for a SerializerMethodField.

Radwan Abu-Odeh
  • 1,897
  • 9
  • 16