Why is my Django serializer returning only Match data and not including related Score data in the API response?
I'm working with Django REST Framework and trying to create an API endpoint that returns live match details along with their associated scores. I have two models, Match and Score, where Score has is associated with Match with a foreignkey. However, when I serialize the Match model, the response only includes match details and does not include any score information.
Here’s what my serializers look like:
class ScoreSerializer(serializers.ModelSerializer):
class Meta:
model = Score
fields = ['id', 'run', 'wickets', 'overs']
class MatchSerializer(serializers.ModelSerializer):
scores = ScoreSerializer(many=True, read_only=True)
class Meta:
model = Match
fields = '__all__'
Here is my view code:
def livematch(request):
live_matches = Match.objects.filter(match_mode='Live')
serializer = MatchSerializer(live_matches, many=True)
return Response({'success': True, 'data': serializer.data})
The default related name score_set
, so:
class MatchSerializer(serializers.ModelSerializer):
score_set = ScoreSerializer(many=True, read_only=True)
class Meta:
model = Match
fields = '__all__'
or you can use score_set
as source:
class MatchSerializer(serializers.ModelSerializer):
scores = ScoreSerializer(many=True, read_only=True, source='score_set')
class Meta:
model = Match
fields = '__all__'
In the view, please use .prefetch_related(..)
to speed up querying:
def livematch(request):
live_matches = Match.objects.filter(match_mode='Live').prefetch_related('score_set')
serializer = MatchSerializer(live_matches, many=True)
return Response({'success': True, 'data': serializer.data})