[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"

4πŸ‘

βœ…

I would consider changing the serializer as below,

class VideoManageSerializer(serializers.ModelSerializer):
    video_tag_id = serializers.PrimaryKeyRelatedField(
        many=True,
        queryset=VideoTag.objects.all(),
        write_only=True,
    )
    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)
    {
       "deleted":false,
       "publishedOn":"2022-11-28",
       "decoratedThumbnail":"https://t3.ftcdn.net/jpg/02/48/42/64/360_F_248426448_NVKLywWqArG2ADUxDq6QprtIzsF82dMF.jpg",
       "rawThumbnail":"https://t3.ftcdn.net/jpg/02/48/42/64/360_F_248426448_NVKLywWqArG2ADUxDq6QprtIzsF82dMF.jpg",
       "videoUrl":"https://www.youtube.com/watch?v=jNQXAC9IVRw",
       "title":"Video with tags",
       "duration":120,
       "visibility":1,
       "video_tag_id":[1,2,3]
    }
    

Refs

  1. DRF: Simple foreign key assignment with nested serializer?
  2. DRF – write_only
  3. DRF – read_only
πŸ‘€JPG

Leave a comment