gpt4 book ai didi

Django Rest 框架 : PUT/POST fails in case of blank optional fields in nested serializer

转载 作者:行者123 更新时间:2023-12-01 15:48:14 25 4
gpt4 key购买 nike

我正在使用 Django 1.7 版和 Django Rest 框架 3.1.3 版。

我有两个相互关联的模型,如下所示:

class Person(models.Model):
name = models.CharField(max_length=200)
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('T', 'Transgender'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
address = models.CharField(max_length=1000)
work_phone = models.CharField(max_length=15, blank=True, null=True,
validators=[RegexValidator(regex='^[0-9]+$',
message='Phone number must contain only digits',
code='nomatch')])
home_phone = models.CharField(max_length=15, blank=True, null=True,
validators=[RegexValidator(regex='^[0-9]+$',
message='Phone number must contain only digits',
code='nomatch')])
mobile = models.CharField(max_length=15, blank=True, null=True,
validators=[RegexValidator(regex='^[0-9]+$',
message='Phone number must contain only digits',
code='nomatch')])
email = models.EmailField(blank=True)
date_of_birth = models.DateField()
user = OneToOneField(User, null=True, blank=True)
DOCUMENT_CHOICES = (
('DL', 'Driving License'),
('RC', 'Ration card'),
('PP', 'Passport'),
('NO', 'None'),
)
additional_document = models.CharField(max_length=2, choices=DOCUMENT_CHOICES)
document_number = models.CharField(max_length=10, blank=True, null=True)
document_scan = models.FileField(max_length=1000, blank=True, null=True)
photo = models.ImageField(blank=True,null=True)

class Admin(models.Model):
person = OneToOneField(Person)
# More fields will be added later

因此,Person 包含一个指向 User(Django 的 auth_user 模型)的 OneToOne 字段,而 Admin 包含一个指向 Person 的 OneToOne 字段。但是,我想为最终用户提供一个屏幕来一次性更新所有这些细节(类似于在一个模板中组合多个 ModelForm)。

我已经创建了与这些模型中的每一个相对应的显式序列化程序,它们具有如下嵌套关系。
class UserSerializer(serializers.Serializer):
id = serializers.IntegerField(label='ID', read_only=True)
username = serializers.CharField(max_length=30)
password = serializers.CharField(max_length=128, style={'input_type': 'password'})

class PersonSerializer(serializers.Serializer):
id = serializers.IntegerField(label="ID", read_only=True)
user = UserSerializer()
name = serializers.CharField(max_length=200)
gender = serializers.ChoiceField(choices=['M', 'F', 'T'])
address = serializers.CharField(max_length=1000)
work_phone = serializers.CharField(max_length=15, required=False, allow_null=True)
home_phone = serializers.CharField(max_length=15, required=False, allow_null=True)
mobile = serializers.CharField(max_length=15, required=False, allow_null=True)
email = serializers.EmailField(required=False, allow_blank=True)
date_of_birth = serializers.DateField()
additional_document = serializers.ChoiceField(choices=['NO','DL', 'RC', 'PP'])
document_number = serializers.CharField(max_length=10, required=False, allow_null=True)
document_scan = serializers.FileField(max_length=1000, required=False, allow_null=True)
photo = serializers.ImageField(required=False, allow_null=True)


class AdminSerializer(serializers.Serializer):
id = serializers.IntegerField(label="ID", read_only=True)
person = PersonSerializer()
# More fields will be added later

每个序列化程序都定义了一个显式的 create() 和 update() 方法,为了简洁起见,我省略了这些方法。我可以看到这些没有被调用,所以在验证过程中可能会遇到错误。

当我执行 GET 操作时,Person 或 Admin api 端点正确返回所有嵌套对象。

当我对 Person 执行 PUT 或 POST 操作时,它接受可选字段中的空白输入。但是,如果我在对 Admin 对象执行 PUT 或 POST 操作时将相同的字段保留为空白,则会如下标记错误。

我的 PUT 请求是:
{
"id": 1,
"person": {
"id": 1,
"user": {
"id": 2,
"username": "nina.sinha",
"password": "pbkdf2_sha256$12000$CjmifxpP1DDv$1622S7enIwnT+NcwhMKIEWrq8Uy7gQQJPQQueML21Sg="
},
"name": "Nina Sinha",
"gender": "F",
"address": "1234, 6th Cross, 7th Main Street",
"work_phone": "42011567",
"home_phone": "",
"mobile": "9854609658",
"email": "nina.sinha@yahoo.com",
"date_of_birth": "1985-04-03",
"additional_document": "NO",
"document_number": "",
"document_scan": null,
"photo": null
}
}

错误:
HTTP 400 Bad Request
Content-Type: application/json
Vary: Accept
Allow: GET, PUT, PATCH, HEAD, OPTIONS

{
"person": {
"document_scan": [
"The submitted data was not a file. Check the encoding type on the form."
],
"photo": [
"The submitted data was not a file. Check the encoding type on the form."
],
"document_number": [
"This field may not be blank."
],
"user": [
"This field is required."
],
"home_phone": [
"This field may not be blank."
]
}
}

字段 document_scan、document_number 和 home_phone 留空,但它们是可选字段,AdminSerializer 应该接受这一点。

已经输入了与用户相关的字段,但我仍然收到错误“此字段是必需的”,好像它们丢失了一样。

我在这里缺少什么?如果我使用 ModelSerializers,我会面临同样的问题。

最佳答案

查看您的代码为什么不使用模型序列化器而不是序列化器。在序列化程序级别,您可以根据要求更改字段。您可以在序列化程序中将必填字段更改为非必填字段,并且在模型级别不会出现问题。

序列化程序.py

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password')

class PersonSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Person
fields = ('id', 'user', # specify other fields)

class AdminSerializer(serializers.ModelSerializer):
person = PersonSerializer()
class Meta:
model = Admin
fields = ('id', 'person', # specify other fields)

如果要将 PersonSerializer 中的用户字段更改为非必需字段,请按如下所示更改代码。
user = UserSerializer(required=False)

关于Django Rest 框架 : PUT/POST fails in case of blank optional fields in nested serializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31582562/

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