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