Issue
With django-rest-framework, how can I serialize the many elements of a one-to-many relationship into a list of simple values from one field of those items? For example in
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')
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
I would like to get
{
'album_name': 'Things We Lost In The Fire',
'artist': 'Low',
'tracks': [15, 12, 17, 23]
}
Solution
Use PrimaryKeyRelatedField(...)
as
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializer.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
fields = '__all__'
model = Album
Answered By - JPG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.