1

I have two models defined in my models.py file:

class Album(models.Model):
    album = models.CharField(max_length=100)
    band = models.CharField(max_length=100)

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    song = models.CharField(max_length=100)

For these, I have defined the serializers in my serializers.py file as:

class AlbumSerializer(serializers.ModelSerializer):
    class Meta:
        model = Album
        fields = "__all__"


class SongSerializer(serializers.ModelSerializer):
    album = AlbumSerializer()
    class Meta:
        model = Song
        fields = "__all__"

When I make a request, the data I get is in this format:

[
    {
        "id": 1,
        "album": {
            "id": 1,
            "album": "Hybrid Theory",
            "band": "Linkin Park"
        },
        "song": "Numb"
    },
    {
        "id": 2,
        "album": {
            "id": 1,
            "album": "Hybrid Theory",
            "band": "Linkin Park"
        },
        "song": "In the End"
    }
]

How do I remove the nesting from the album name, from the songs Serializer? I would want data something like this:

[
    {
        "id": 1,
        "album_id": 1,
        "album": "Hybrid Theory",
        "band": "Linkin Park"
        "song": "Numb"
    },
    {
        "id": 2,
        "album_id": 1,
        "album": "Hybrid Theory",
        "band": "Linkin Park"
        "song": "In the End"
    }
]
1
  • you can override to_representation() to get a different behaviour of your data that you want to display. Commented May 17, 2021 at 9:43

2 Answers 2

1

SongSerializer

  1. remove album = AlbumSerializer()

  2. override method to_representation

from django.forms import model_to_dict

def to_representation(self, instance):
        song = super().to_representation(instance)
        album = model_to_dict(instance.album)
        for key, value in album.items():
           setattr(song, key, value)
        return song

I did not test the code.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

class SongSerializer(serializers.ModelSerializer):
    album_id = serializers.SerializerMethodField(source='album.id')
    album = serializers.SerializerMethodField(source='album.album')
    band = serializers.SerializerMethodField(source='album.band')

    class Meta:
        model = Song
        fields = ['album_id', 'album', 'band', .....]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.