django-rest-framework如何使模型序列化器字段必填 [英] django-rest-framework how to make model serializer fields required

查看:284
本文介绍了django-rest-framework如何使模型序列化器字段必填的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a model that I'm filling out step by step, it means I'm making a form wizard.

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

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.

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

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.

推荐答案

您需要专门覆盖该字段并添加您自己的验证器.您可以在此处详细了解 http://www .django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly .这是示例代码.

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.

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

这篇关于django-rest-framework如何使模型序列化器字段必填的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆