'How to deal with unsaved nested models in serializer?
My input is a JSON object that represents a video channel. It has some simple fields and fields that contain an array e.g. tags.
What I want to accomplish is parse the JSON, turn it into a Channel model object that a tags property with a list of Tag model objects. I set it up as a many to many relationship.
Tag has only 1 field: title, but the JSON input is an anonymous array like "tags": ["tag1", "tag2",...].
On channelSerializer.is_valid(), it fails. Hacking around, I converted the input from "tags": ["tag1"] to "tags": ["title": "tag"] which worked but I don't like hacky solutions.
I'm at a point of making a service, pull out tags, create a channel objects, convert tags independently and add it to channel...but I feel I'm missing a better, standard method.
What is the recommended approach for this situation in Django?
Code that definitely has some issues:
class Tag(models.Model):
title = models.CharField(unique=True, null=True, blank=True, max_length=255)
class Meta:
db_table = "tag"
class Channel(models.Model):
tags = models.ManyToManyField(Tag)
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ['title']
def create(self, validated_data):
return Tag.objects.create(title=validated_data)
class ChannelSerializer(serializers.ModelSerializer):
tags = TagSerializer(many=True, read_only=False, required=False)
class Meta:
model = Channel
fields = '__all__'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
