Home > Back-end >  How to serialize a list of objects into list of items for primary key
How to serialize a list of objects into list of items for primary key

Time:11-03

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]
}

CodePudding user response:

Use PrimaryKeyRelatedField(...) as

class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializer.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        fields = '__all__'
        model = Album
  • Related