【问题标题】:django-rest-framework how to make model serializer fields requireddjango-rest-framework 如何使模型序列化器字段成为必需
【发布时间】:2015-09-06 08:12:41
【问题描述】:

我有一个模型,我正在一步一步填写,这意味着我正在制作一个表单向导。

因为此模型中的大多数字段都是必需的,但有null=True, blank=True 以避免在提交部分数据时引发非空错误。

我正在使用 Angular.js 和 django-rest-framework,我需要告诉 api x 和 y 字段应该是必需的,如果它们为空,它需要返回验证错误。

【问题讨论】:

    标签: python angularjs django django-rest-framework


    【解决方案1】:

    根据文档here,最好的选择是在 Meta 类中使用 extra_kwargs,例如,您有存储电话号码的 UserProfile 模型,并且是必需的

    class UserProfileSerializer(serializers.ModelSerializer):
        class Meta:
            model = UserProfile
            fields = ('phone_number',)
            extra_kwargs = {'phone_number': {'required': True}} 
    

    【讨论】:

    • 不起作用,即使需要true,也可以创建具有空值的对象
    • @VaibhavVishal,上述解决方案不是避免创建具有NULL值的对象,在模型中如果您有null=True,blank=True,则将创建具有空值的对象。上面的解决方案是返回一个验证错误以将其作为用户级别处理。我相信没有办法避免 ORM 不创建空对象值。
    • 是的,我的错,就我而言,我必须编写一个自定义验证器来检查值是否不是None''。然后同时使用我的自定义验证器和额外的 kwargs,以确保用户通过 api 发送值并且不发送空值。
    • @VaibhavVishal 只需将 'allow_null': False 添加到 extra_kwargs
    【解决方案2】:

    您需要专门覆盖该字段并添加您自己的验证器。您可以在此处阅读更多详细信息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
    

    【讨论】:

      【解决方案3】:

      这是我处理多个字段的方式。它基于重写 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')
                  )
              ]
      

      【讨论】:

        【解决方案4】:

        这在我的后端应用上运行良好。

        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}}
        

        【讨论】:

          【解决方案5】:

          如果您使用的是 CharField,另一种选择是使用 requiredtrim_whitespace

          class CustomObjectSerializer(serializers.Serializer):
              name = serializers.CharField(required=True, trim_whitespace=True)
          

          required 文档:http://www.django-rest-framework.org/api-guide/fields/#required trim_whitespace 医生:http://www.django-rest-framework.org/api-guide/fields/#charfield

          【讨论】:

            【解决方案6】:

            根据link1link2,由于预期字段为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}}
            

            【讨论】:

              猜你喜欢
              • 2013-11-15
              • 2018-06-07
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-10-07
              • 2016-11-14
              • 2016-12-03
              • 1970-01-01
              相关资源
              最近更新 更多