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 β
- Added a new
write_only
field namedvideo_tag_id
that supposed to accept "list of PKs ofVideoTag
". - Changed the
tags
field toread_only
so that it wonβt take part in the validation process, but youβll get the "nested serialized output". - Changed
create(...)
method to cooperate with the new changes. - The POST payload has been changed as below (note that
tags
has been removed andvideo_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
π€JPG
Source:stackexchange.com