Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the parent object in Django Rest Framework serializer

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?

like image 248
user3214546 Avatar asked Jan 08 '15 23:01

user3214546


People also ask

How do I pass Queryset to 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.

How does Django REST framework serializer work?

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.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

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.

What does serializer data return?

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 ).


2 Answers

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.

like image 125
Kevin Brown-Silva Avatar answered Sep 17 '22 21:09

Kevin Brown-Silva


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',)
like image 43
Louis Becker Avatar answered Sep 17 '22 21:09

Louis Becker