Nested Relationships

Asked

Viewed 57 times

1

Guys, I have a question regarding the nested relationship.

When my code gets that way:

 class CategoryListSerializer(ModelSerializer):
    class Meta:
        model = Category
        fields = ['id', 'name', 'created_at']


class BookCreateListSerializer(ModelSerializer):
    category = CategoryListSerializer()

    class Meta:
        model = Book
        fields = ['id', 'name', 'created_at', 'category']

Returns like this:

inserir a descrição da imagem aqui

When I comment on the category = CategoryListSerializer()

He returns this way:

inserir a descrição da imagem aqui

I want to understand why this behavior and how I can perform POST this way, because when I insert Category it asks to overwrite the .create()

1 answer

2


By default, nested serializers are read-only. If you want to support write operations in a nested serializer field, you need to create create() and/or update() methods to explicitly specify how child relationships should be saved.

example:

 class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['order', 'title', 'duration']

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True)

    class Meta:
        model = Album
        fields = ['album_name', 'artist', 'tracks']

    def create(self, validated_data):
        tracks_data = validated_data.pop('tracks')
        album = Album.objects.create(**validated_data)
        for track_data in tracks_data:
            Track.objects.create(album=album, **track_data)
        return album

If the field is used to represent a relationship for many, you should add the many=True the field of the serializer.

example:

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['order', 'title', 'duration']

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ['album_name', 'artist', 'tracks']

Reference: https://www.django-rest-framework.org/api-guide/relations/

  • So, the weirdest thing that when I do this way of overwriting, I’m forced to create a category and the book. This relates to models?

  • When you create a nested relationship by default it is read-only, i.e., you don’t need to create a category every time you create a book, you just need to associate an existing category. See if you are passing the parameter (read_only=True), like the examples I left.

  • 1

    I just corrected the models, even using read_only was asked to register the category.

  • 1

    your solution just needs a small adjustment, I would use the get_or_create since I don’t always need to create a Track or Album , for example I may want to add a track to an existing album or vice versa django documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.