使用Django 1.11和Django Rest Framework 3.7,我有一个Person模型
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('id', 'name', 'age', 'email')
使用PersonSerializer
class PersonList(generics.ListCreateAPIView):
queryset = Person.objects.all()
serializer_class = PersonSerializer
和ListCreate视图
$ 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"
}
使用HTTPie,我可以像这样创建一个人:
$ 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."
]
}
当我创建一个电子邮件地址错误的人时,我收到错误:
$ 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"
}
DRF知道它是一个EmailField并自动应用验证,到目前为止一直很好。
但是,当我创建一个年龄不佳的人(负数)时,我没有收到任何错误:
for(int i = 0; i < column; i++){
position = keyWord.indexOf(sorted_key[i]); // Here's the problem
for(int j = 0; j < row; j++){
matrix[j][position] = cipher_array[count];
count++; }}
现在我的数据库已被坏数据污染了。我完成验证输入的工作没有问题,但是
基于这些事实,我的问题是:
(A)为什么DRF的序列化程序验证EmailField,而不是PositiveSmallIntegerField?
(B)我应该在哪里验证“年龄”字段以确保它是正面的?模型?串行?查看?
答案 0 :(得分:2)
将验证器添加到模型中的字段:
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)])
答案 1 :(得分:1)
在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')