Answer the question
In order to leave comments, you need to log in
Django REST Framework: Not displaying fields of related objects?
Hello!
Faced with the fact that when serializing a simple object, related objects are not displayed (more precisely, the fields of the related object, except for the ID), as indicated in the Serializer relations
tutorial
Actually, all the code from there
is models.py
class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ('album', 'order')
ordering = ['order']
def __str__(self):
return '%d: %s' % (self.order, self.title)
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.StringRelatedField(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@api_view(['GET',])
@permission_classes((AllowAny,))
def album_list(request):
if request.method == 'GET':
albums = Album.objects.all().prefetch_related('tracks')
album_serializer = AlbumSerializer(albums, many=True)
return Response(album_serializer.data)
Answer the question
In order to leave comments, you need to log in
I will answer myself.
I found the problem in these renders.
'DEFAULT_RENDERER_CLASSES': (
'rest_framework_json_api.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
They manage to make such a mess that child margins are not returned. Killed 1.5 days for this nonsense.
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = '__all__'
class AlbumSerializer(serializers.ModelSerializer):
tracks =TrackSerializer(read_only=True, many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question