gpt4 book ai didi

python - Django RF 错误详细信息 : This field is required with APIClient

转载 作者:行者123 更新时间:2023-12-04 08:10:04 27 4
gpt4 key购买 nike

我正在尝试使用来自发布请求的序列化程序创建对象,但在尝试将对象列表传递给嵌套序列化程序时出现错误。在以 JSON 格式传递 ('id', 'name', 'description') 数据时,bars 列表没有得到正确解析并返回以下错误:

{'bars' : [ErrorDetail(string='This field is required.', code='required')]}}

那些是序列化程序:

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)

这是我的请求负载:

{
'name': "A Foo",
'description': "A happy foo running in the woods of Central Park",
'bars': [
{name : 'a'},
{name : 'b'},
{name : 'c'},
]
}

这些是模型

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)

更新

问题仅在使用 Django python manage.py test 进行测试时出现,而在使用本地服务器使用 postman 测试请求时则不存在

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)

注意 Foo 和 Bar 都是我真实模型的简化模型,以减少给定问题的信息量

最佳答案

在使用 APIClient rest_framework.test.APIClient 测试模型并使用更复杂的数据和嵌套序列化程序发出 post 请求时,格式必须明确设置为 json因此

def test_a_feature(self):
self.client = APIClient()

payload = {
"name": "A Foo",
"description": "A happy foo running in the woods of Central Park",
"bars": [
{name : "a"},
{name : "b"},
{name : "c"},
]
}

self.client.post(reverse('foo-list'), payload, format='json')

关于python - Django RF 错误详细信息 : This field is required with APIClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66019680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com