I'm trying to create an object with a serializer from a post request but I'm getting an error while trying to pass a list of objects to a nested serializer. While passing the ('id', 'name', 'description') data in a JSON format works just fine the list of bars is not getting parsed properly and return the following error :
{'bars' : [ErrorDetail(string='This field is required.', code='required')]}}
Those are the Serializers :
class BarsSerializer(serializers.ModelSerializer):
class Meta:
model = Bar
fields = ('name', 'foo')
class FooSerializer(serializers.ModelSerializer):
bars = BarsSerializer(many=True)
class Meta:
model = Foo
fields = ('id', 'author' 'name', 'description', 'bars')
def create(self, validated_data):
validated_data['author'] = self.context['request'].user
# Foo object manager is tested and works
return Foo.objects.create(**validated_data)
This is my request payload :
{
'name': "A Foo",
'description': "A happy foo running in the woods of Central Park",
'bars': [
{name : 'a'},
{name : 'b'},
{name : 'c'},
]
}
Those are the models
class Bar(models.Model):
name = models.CharField(
max_length=255,
default=""
)
foo = models.ForeignKey(
Foo,
related_name='foos',
on_delete=models.CASCADE
)
class Foo(models.Model):
name = models.CharField(
max_length=255
)
description = models.CharField(
max_length=1023,
default=""
)
author = models.ForeignKey(CommonUser, on_delete=models.SET_NULL, null=True)
Update
the problem is only there while testing with Django python manage.py test and not there while testing the request with postman with the local server
data = {
"name": "A Foo",
"description": "A happy foo running in the woods of Central Park",
"bars": [
{name : "a"},
{name : "b"},
{name : "c"},
]
}
res = self.client_one.post(reverse('foo-list'), data)
note that Foo and Bar are both simplified model of my real models to reduce the information amount of the given problem