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

时间:2022-07-14 19:37:35

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字段应该是必需的,如果它们是空的,它需要返回验证错误。

4 个解决方案

#1


6  

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. This is the example code.

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

#2


12  

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

#3


5  

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')
            )
        ]

#4


1  

Another option is to use required and trim_whitespace if you're using a CharField:

如果您使用的是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

所需文件:http://www.django-rest-framework.org/api-guide/fields/#required trim_whitespace doc:http://www.django-rest-framework.org/api-guide/fields/#charfield

#1


6  

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. This is the example code.

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

#2


12  

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

#3


5  

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')
            )
        ]

#4


1  

Another option is to use required and trim_whitespace if you're using a CharField:

如果您使用的是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

所需文件:http://www.django-rest-framework.org/api-guide/fields/#required trim_whitespace doc:http://www.django-rest-framework.org/api-guide/fields/#charfield