1

I have setup my serializer to return nested content successfully.

However, I have not been able to post data within the nested fields.

I don't get an error when posting the data- but it only posts to the non-nested fields.

I would like for it to take the "name" field OR primary key (of model "TAG") for posting item.

Models.py

class Tag(models.Model):
    name = models.CharField("Name", max_length=5000, blank=True)
    def __str__(self):
        return self.name

class Movie(models.Model):
    title = models.CharField("Whats happening?", max_length=100, blank=True)
    tag = models.ManyToManyField('Tag', blank=True)
    def __str__(self):
        return self.title

Serializers.py:

class TagSerializer(serializers.ModelSerializer):
    taglevel = filters.CharFilter(taglevel="taglevel")
    class Meta:
        model = Tag
        fields = ('name', 'taglevel', 'id')

class MovieSerializer(serializers.ModelSerializer):
    tag = TagSerializer(many=True, read_only=False)
    info = InfoSerializer(many=True, read_only=True)
    class Meta:
        model = Movie
        fields = ('title', 'tag', 'info')

def validate(self, data):
    print(self.initial_data.__dict__)
    data['tag_name'] = []
    if 'tag' in self.initial_data.keys():
        for entry in self.initial_data['tag']:     
            data['tag_name'].append(entry['name'])
    return data

def create(self, validated_data):
    print(validated_data)
    tags_data = validated_data.pop('tag')
    movie = Task.objects.create(**validated_data)
    for tag_data in tags_data:
        Movie.objects.create(name=name, **tag_data)
    return movie

Sample of posting data:

r = requests.post('http://localhost:8000/api/Data/',{ "title": "TEST_title", "tag": [ { "name": "test1", "name": "test2" } ], "info": [] })
0

1 Answer 1

1

Your json should be.

{ 
"title": "TEST_title", 
"tag": [ {"name": "test1" },
        {"name": "test2"}
       ],
"info": []
}

class TagSerializer(serializers.ModelSerializer):
    taglevel = filters.CharFilter(taglevel="taglevel")

    class Meta:
        model = Tag
        fields = ('name', 'taglevel', 'id')


class MovieSerializer(serializers.ModelSerializer):
    tag = TagSerializer(many=True, read_only=False)
    info = InfoSerializer(many=True, read_only=True)

    class Meta:
        model = Movie
        fields = ('title', 'tag')

    def create(self, validated_data):
        tags_data = validated_data.pop('tag')
        movie = Movie.objects.create(**validated_data)
        for tag_data in tags_data:
            movie.tag.create(**tag_data)
        return movie
Sign up to request clarification or add additional context in comments.

3 Comments

This has not worked. I get a 500 error (traceback here-dpaste.com/0BB0ZE8). So I changed "tag = " to "read_only=False". This no longer gave the 500 error- but only posted the non-nested data.
Sorry i didn't test it at first. But i tested it now, though i had to omit (for my testing) the taglevel field on the Tag serializer. But i also realized that your json data you're posting for tags aren't correct either. 1. you have duplicate keys in the dictionary. But this is how you'll create tags for a created movie,
Same issue again. Only posting data to the non-nested fields. I'm posting like this- r = requests.post('localhost:8000/api/Data',{ "title": "TEST_title", "tag": [ {"name": "test1" }, {"name": "test2"} ], "info": [] })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.