class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('phone_number',)
extra_kwargs = {'phone_number': {'required': True}}
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
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')
)
]
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password')
extra_kwargs = {'email': {'required': True,
'allow_blank': False}}
6条答案
按热度按时间ktca8awb1#
根据这里的文档,最好的选择是在 meta中使用extra_kwargs,例如,您有存储电话号码的UserProfile模型,并且是必需的
要使其正常工作,请确保您的模型已设置为blank false null false,如下所示。
63lcw9qa2#
你需要特别地覆盖这个字段并添加你自己的验证器。你可以在这里阅读更多的细节http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly。这是示例代码。
wixjitnu3#
这是我处理多个字段的方法。它基于重写UniqueTogetherValidator。
用法:
fnvucqvd4#
这在我的后端应用程序上运行得非常好。
7uzetpgm5#
另一种选择是,如果您使用字符域,则使用
required
和trim_whitespace
:required
文档:http://www.django-rest-framework.org/api-guide/fields/#requiredtrim_whitespace
文档:http://www.django-rest-framework.org/api-guide/fields/#charfieldscyqe7ek6#
根据link1和link2,并且由于预期字段是
null=True, blank=True
(就像我的示例中django.contrib.auth.models.User
的email
字段),这将起作用: