Hi Everyone,
Conside the following case
class Album(models.Model):
name = models.CharField(max_length=20)
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks')
I need to create TrackSerializer,
class TrackSeriallizer(serializers.ModelSerializer):
class Meta:
model = Track
Here by default, album field will be treated as PrimayKeyRelatedField. So the serialized data would some like
{
'id': 1,
'album':1
}
but I wanted to be
{
'id': 1,
'album': {
'id': 1,
'name': 'album1'
}
}
I am aware that I could use nested serializer as below to achive this, but then I cannot create Track instance just by passing album id
class TrackSeriallizer(serializers.ModelSerializer):
album = AlbumSerializer()
class Meta:
model = Track
Can I create a TrackSerializer, so that whenever I get a list of Tracks I wants Album for the track to be nested. But while creating a Track, I should be able to pass album as id(PrimaryKeyRelation)?
Help me figuring out. Thanks in advance