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})
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})
Share
Improve this question
asked 2 days ago
Aalok karnAalok karn
716 bronze badges
1
- Share the corresponding models. – willeM_ Van Onsem Commented 2 days ago
1 Answer
Reset to default 1The 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})