Kaviraj Kanagaraj
2015-09-02 16:09:04 UTC
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
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
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.