简体   繁体   English

django-rest-framework 如何使模型序列化器字段成为必需

[英]django-rest-framework how to make model serializer fields required

I have a model that I'm filling out step by step, it means I'm making a form wizard.我有一个我正在逐步填写的模型,这意味着我正在制作一个表单向导。

Because of that most fields in this model are required but have null=True, blank=True to avoid raising not null errors when submitting part of the data.因为这个模型中的大多数字段都是必需的,但有null=True, blank=True以避免在提交部分数据时引发非空错误。

I'm working with Angular.js and django-rest-framework and what I need is to tell the api that x and y fields should be required and it needs to return a validation error if they're empty.我正在使用 Angular.js 和 django-rest-framework,我需要告诉 api x 和 y 字段应该是必需的,如果它们为空,它需要返回验证错误。

The best option according to docs here is to use extra_kwargs in class Meta, For example you have UserProfile model that stores phone number and is required根据此处文档的最佳选择是在类 Meta 中使用 extra_kwargs,例如您有 UserProfile 模型,该模型存储电话号码并且是必需的

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

You need to override the field specifically and add your own validator.您需要专门覆盖该字段并添加您自己的验证器。 You can read here for more detail http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly .你可以在这里阅读更多细节http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly This is the example code.这是示例代码。

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

This is my way for multiple fields.这是我对多个领域的方式。 It based on rewriting UniqueTogetherValidator.它基于重写 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)
        ))

Usage:用法:

class MyUserRegistrationSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ( 'email', 'first_name', 'password' )
        validators = [
            RequiredValidator(
                fields=('email', 'first_name', 'password')
            )
        ]

This works very well on my backend app.这在我的后端应用程序上非常有效。

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

Another option is to use required and trim_whitespace if you're using a CharField:如果您使用的是 CharField,另一种选择是使用requiredtrim_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 required文档:http ://www.django-rest-framework.org/api-guide/fields/#required trim_whitespace文档: http : //www.django-rest-framework.org/api-guide/fields/#charfield

According to link1 and link2 , and due to the intended field is null=True, blank=True (like email field of django.contrib.auth.models.User in my example) this will work:根据link1link2 ,并且由于预期字段为null=True, blank=True (如我示例中的django.contrib.auth.models.User email字段)这将起作用:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('username', 'email', 'password')
        extra_kwargs = {'email': {'required': True,
                                  'allow_blank': False}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用django-rest-framework在序列化程序级别上扩展模型 - How to extend model on serializer level with django-rest-framework 将动态字段添加到Django-rest-framework中的序列化器 - Adding dynamic fields to a serializer in django-rest-framework 根据django-rest-framework序列化器中的请求显示字段 - Display fields based on the request in django-rest-framework serializer Django 休息框架序列化程序:required_fields - Django rest framework serializer: required_fields 如何在Django-rest-framework序列化器中的关系模型中获得额外的列? - How to get an extra column in relational model in Django-rest-framework serializer? 如何编写django-rest-framework序列化程序以保存包含通用模型的嵌套层次结构? - How do I write a django-rest-framework serializer to save a nested hierarchy containing a generic model? 如何在 django-rest-framework 的序列化器中使用时区序列化时间? - how to serialize time with timezone in django-rest-framework's serializer? 如何在django-rest-framework中将参数传递给序列化器? - How to pass arguments to a Serializer in django-rest-framework? 如何在Django-rest-framework中序列化列表? - how can I serializer a list in django-rest-framework? Django Rest Framework:派生模型序列化器字段 - Django Rest Framework: Derived model serializer fields
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM