2015-06-20 109 views
7

我有一個模型,我一步一步地填寫,這意味着我正在製作一個表單嚮導。django-rest-framework如何讓模型序列化字段需要

因爲這個模型中的大多數字段都是必需的,但有null=True, blank=True以避免在提交部分數據時引發非空錯誤。

我正在使用Angular.js和django-rest-framework,我需要的是告訴api x和y字段應該是必需的,如果它們爲空,它需要返回一個驗證錯誤。

回答

4

這是我對多個領域的方法。它基於重寫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') 
      ) 
     ] 
9

根據文檔here最好的選擇是使用類元extra_kwargs,比如你有一個存儲電話號碼和需要用戶配置模型

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