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.
因为此模型中的大多数字段都是必需的,但具有 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屋!