How can I get the parent 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 the album.

 class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('album__name') 

Does not work

I do not want to declare an AlbumSerializer for this. is there any way to do this without undoing the new serializer

+5
source share
3 answers

You can do this by creating a field on the TrackSerializer that has a custom source that retrieves the album name.

The name of the attribute that will be used to populate the field. It can be a method that takes only its own argument, such as URLField ('get_absolute_url'), or it can use dotted notations to move attributes such as EmailField (source = 'user.email).

So, in your case, your field should be added ( album_name in this case) using a 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 name of the output album under the album_name key.

+10
source

You can do it like this (using Python dynamics):

 def create_serializer(target_class, fields): class ModelSerializer(serializers.ModelSerializer): class Meta: model = target_class fields = fields return ModelSerializer 

Thus, a path serializer can be created using this approach:

 TrackSerializer = create_serializer(Track, ('album__name',)) 

Also, be careful with ('album__name') , which is a string expression in brackets, not a tuple as you probably intended. To declare it as a tuple, add it after the comma, for example:

 fields = ('album__name',) 
0
source

It looks like you need a Serializer relationship .

Also a question very similar to this one arises: django rest framework view does not display related table data

-2
source

Source: https://habr.com/ru/post/1210701/


All Articles