Python django rest框架如何使模型序列化器字段成为必需字段
我有一个模型,我正在一步一步地填写,这意味着我正在制作一个表单向导 因为此模型中的大多数字段都是必需的,但都具有Python django rest框架如何使模型序列化器字段成为必需字段,python,angularjs,django,django-rest-framework,Python,Angularjs,Django,Django Rest Framework,我有一个模型,我正在一步一步地填写,这意味着我正在制作一个表单向导 因为此模型中的大多数字段都是必需的,但都具有null=True、blank=True,以避免在提交部分数据时引发非null错误 我正在使用Angular.js和django rest框架,我需要告诉api应该需要x和y字段,如果它们是空的,它需要返回一个验证错误。您需要专门覆盖该字段并添加您自己的验证器。你可以在这里阅读更多细节。这是示例代码 def required(value): if value is None:
null=True、blank=True
,以避免在提交部分数据时引发非null错误
我正在使用Angular.js和django rest框架,我需要告诉api应该需要x和y字段,如果它们是空的,它需要返回一个验证错误。您需要专门覆盖该字段并添加您自己的验证器。你可以在这里阅读更多细节。这是示例代码
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)
))
根据文档,最好的选择是在Meta类中使用额外的_kwargs,例如,您有存储电话号码的UserProfile模型,这是必需的
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('phone_number',)
extra_kwargs = {'phone_number': {'required': True}}
另一种选择是使用
必填
和修剪空白
,如果您使用的是字符字段:
class CustomObjectSerializer(serializers.Serializer):
name = serializers.CharField(required=True, trim_whitespace=True)
必需
文件:
trim_whitespace
doc:根据和,由于预期字段为null=True,blank=True
(如email
字段的django.contrib.auth.models.User
,在我的示例中)这将起作用:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password')
extra_kwargs = {'email': {'required': True,
'allow_blank': False}}
这在我的后端应用程序上非常有效
class SignupSerializer(serializers.ModelSerializer):
""" Serializer User Signup """
class Meta:
model = User
fields = ['username', 'password', 'password', 'first_name', 'last_name', 'email']
extra_kwargs = {'first_name': {'required': True, 'allow_blank': False}}
extra_kwargs = {'last_name': {'required': True,'allow_blank': False}}
extra_kwargs = {'email': {'required': True,'allow_blank': False}}
不起作用,即使使用必需的true,也可以使用空值的对象created@VaibhavVishal,上述解决方案不是为了避免创建具有空值的对象,在模型中,如果您具有NULL=True,blank=True,则将使用空值创建对象。上面的解决方案是返回一个验证错误,将其作为用户级别处理。我相信没有办法避免ORM不创建空的对象值。是的,我的错,在我的情况下,我必须编写一个自定义验证器来检查值是否为非
None
或'
。然后同时使用“我的自定义验证器”和“额外kwargs”(必需),以确保用户通过api发送值,而不是发送空值。@VaibhavVishal只需添加“允许null”:对额外kwargs为False
class SignupSerializer(serializers.ModelSerializer):
""" Serializer User Signup """
class Meta:
model = User
fields = ['username', 'password', 'password', 'first_name', 'last_name', 'email']
extra_kwargs = {'first_name': {'required': True, 'allow_blank': False}}
extra_kwargs = {'last_name': {'required': True,'allow_blank': False}}
extra_kwargs = {'email': {'required': True,'allow_blank': False}}