[Django]-Django – Sending post request using a nested serializer with many to many relationship. Getting a [400 error code] "This field may not be null] error"



I would consider changing the serializer as below,

class VideoManageSerializer(serializers.ModelSerializer):
    video_tag_id = serializers.PrimaryKeyRelatedField(
    tags = VideoVideoTagSerializer(many=True, read_only=True)

    class Meta:
        model = Video
        fields = "__all__"

    # POST
    def create(self, validated_data):
        tags = validated_data.pop("video_tag_id")
        video_instance = Video.objects.create(**validated_data)
        for tag in tags:
            VideoVideoTag.objects.create(videoId=video_instance, videoTagId=tag)
        return video_instance

Things that have changed –

  1. Added a new write_only field named video_tag_id that supposed to accept "list of PKs of VideoTag".
  2. Changed the tags field to read_only so that it won’t take part in the validation process, but you’ll get the "nested serialized output".
  3. Changed create(...) method to cooperate with the new changes.
  4. The POST payload has been changed as below (note that tags has been removed and video_tag_id has been introduced)
       "title":"Video with tags",


  1. DRF: Simple foreign key assignment with nested serializer?
  2. DRF – write_only
  3. DRF – read_only

Leave a comment