I have this model:
class Track(models.Model):
album = models.ForeignKey(Album)
Now in my TrackSerializer
I want to get the name of album.
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('album__name')
It's not working.
I don't want to declare AlbumSerializer for that. Is there any way to do that without declaring a new serializer?
To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
The BaseSerializer class caches its data attribute on the object, but Serializer. data returns a copy of BaseSerializer. data every time it is accessed (via ReturnDict ).
You can do this by creating a field on your TrackSerializer
that has a custom source
that retrieves the album name.
The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField('get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email').
So in your case, the field album_name
would need to be added with the custom source
set
class TrackSerializer(serializers.ModelSerializer):
album_name = serializers.CharField(read_only=True, source="album.name")
class Meta:
model = Track
fields = ("album_name", )
This will include the album name in the output under the key album_name
.
To include the parent relation you only need to include its serializer and include it in the fields list.
Class TrackSerializer(ModelSerializer):
album = AlbumSerializer()
class Meta:
model = Track
fields = ('name', 'year', 'album',)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With