[英]Why doesn't DRF's serializer validate PositiveSmallIntegerField?
使用Django 1.11和Django Rest Framework 3.7,我有一个Person模型
class Person(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
age = models.PositiveSmallIntegerField()
与PersonSerializer
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('id', 'name', 'age', 'email')
和一个ListCreate视图
class PersonList(generics.ListCreateAPIView):
queryset = Person.objects.all()
serializer_class = PersonSerializer
使用HTTPie,我可以这样创建一个Person:
$ http POST http://127.0.0.1:8000/api/people/ name=Alice age=26 email=alice@example.com
HTTP/1.0 201 Created
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 60
Content-Type: application/json
Date: Sun, 10 Dec 2017 15:00:28 GMT
Server: WSGIServer/0.1 Python/2.7.11
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
{
"age": 26,
"email": "alice@example.com",
"id": 1,
"name": "Alice"
}
当我创建一个人的电子邮件地址错误时,出现错误:
$ http POST http://127.0.0.1:8000/api/people/ name=Bob age=33 email=oops
HTTP/1.0 400 Bad Request
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 42
Content-Type: application/json
Date: Sun, 10 Dec 2017 15:01:08 GMT
Server: WSGIServer/0.1 Python/2.7.11
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
{
"email": [
"Enter a valid email address."
]
}
到目前为止,DRF知道这是一个EmailField并自动应用验证。
但是,当我创建一个年龄不佳(负数)的人时,我没有收到任何错误消息:
$ http POST http://127.0.0.1:8000/api/people/ name=Charlie age=-10 email=charlie@example
.com
HTTP/1.0 201 Created
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 65
Content-Type: application/json
Date: Sun, 10 Dec 2017 15:03:25 GMT
Server: WSGIServer/0.1 Python/2.7.11
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
{
"age": -10,
"email": "charlie@example.com",
"id": 3,
"name": "Charlie"
}
现在,我的数据库已被不良数据污染。 我可以毫无疑问地完成我的输入,但是
基于这些事实,我的问题是:
(A)为什么DRF的序列化程序验证EmailField,而不验证PositiveSmallIntegerField?
(B)我应该在哪里验证“年龄”字段以确保它是肯定的? 模型? 序列化器? 视图?
在模型的字段中添加验证器:
from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator
class Person(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
age = models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(120)])
在DRF中,IntegerField对应于PositiveIntegerField,因此您可以对其设置最大值和最小值限制。
例如:
class PersonSerializer(serializers.ModelSerializer):
age = serializers.IntegerField(max_value=100, min_value=1)
class Meta:
model = Person
fields = ('id', 'name', 'age', 'email')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.