我有一个模型,我一步一步地填写,这意味着我正在制作一个表单向导。django-rest-framework如何让模型序列化字段需要
因为这个模型中的大多数字段都是必需的,但有null=True, blank=True
以避免在提交部分数据时引发非空错误。
我正在使用Angular.js和django-rest-framework,我需要的是告诉api x和y字段应该是必需的,如果它们为空,它需要返回一个验证错误。
我有一个模型,我一步一步地填写,这意味着我正在制作一个表单向导。django-rest-framework如何让模型序列化字段需要
因为这个模型中的大多数字段都是必需的,但有null=True, blank=True
以避免在提交部分数据时引发非空错误。
我正在使用Angular.js和django-rest-framework,我需要的是告诉api x和y字段应该是必需的,如果它们为空,它需要返回一个验证错误。
你需要重写该字段,并添加自己的验证器。你可以在这里阅读更多的细节http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly。这是示例代码。
def required(value):
if value is None:
raise serializers.ValidationError('This field is required')
class GameRecord(serializers.ModelSerializer):
score = IntegerField(validators=[required])
class Meta:
model = Game
这是我对多个领域的方法。它基于重写UniqueTogetherValidator。
from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import ValidationError
from rest_framework.utils.representation import smart_repr
from rest_framework.compat import unicode_to_repr
class RequiredValidator(object):
missing_message = _('This field is required')
def __init__(self, fields):
self.fields = fields
def enforce_required_fields(self, attrs):
missing = dict([
(field_name, self.missing_message)
for field_name in self.fields
if field_name not in attrs
])
if missing:
raise ValidationError(missing)
def __call__(self, attrs):
self.enforce_required_fields(attrs)
def __repr__(self):
return unicode_to_repr('<%s(fields=%s)>' % (
self.__class__.__name__,
smart_repr(self.fields)
))
用法:
class MyUserRegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'first_name', 'password')
validators = [
RequiredValidator(
fields=('email', 'first_name', 'password')
)
]
根据文档here最好的选择是使用类元extra_kwargs,比如你有一个存储电话号码和需要用户配置模型
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('phone_number',)
extra_kwargs = {'phone_number': {'required': True}}
如果您使用CharField,另一种选择是使用required
和trim_whitespace
:
class CustomObjectSerializer(serializers.Serializer):
name = serializers.CharField(required=True, trim_whitespace=True)
required
DOC:http://www.django-rest-framework.org/api-guide/fields/#required trim_whitespace
DOC:http://www.django-rest-framework.org/api-guide/fields/#charfield