Reputation: 55
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"
}
]
Upvotes: 1
Views: 653
Reputation: 646
remove album = AlbumSerializer()
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.
Upvotes: 1
Reputation: 571
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', .....]
Upvotes: 0