Home > Blockchain >  How do I post on a django model when it has another model (manytomany ) inside nested serializers, I
How do I post on a django model when it has another model (manytomany ) inside nested serializers, I

Time:11-17

My models are:

  1. Period
  2. ClassStudentSubject

Period has a manytomany relationship with ClassStudentSubject

When I POST a period I don't want to choose which existing ClassStudentSubject object I use, I want to create a new one together with the period.

ClassStudentSubject - I created this model for the sake of structuring some data of period into an object

CodePudding user response:

I was able to solve my problem referencing this from the documentation:

https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

CodePudding user response:

This can be achieved by overriding create method of the serializer. You have to create "ClassStudentSubject" object first and then use that object while creating Period object in "create" method. Here is the below example from the doc suiting your requirement.

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
  • Related