[英]Django rest framework conditionally required fields
我想寫一個drf驗證器 ,它將根據其他字段的值標記一個字段。 例如:
class MySerializer(serializers.Serializer):
has_children = fields.BooleanField()
nb_childs = fields.IntegerField(min_value=1, validators=[RequiredIf(field='has_children', value=True)], required=False)
起初我認為基於類的驗證器是這樣做的方法,通過這樣的方法檢索'has_children'的值:
def set_context(self, serializer_field):
print serializer_field.parent.initial_data
但是'initial_data'沒有設置。 任何線索?
在DRF文檔中查看
基本上,要進行對象級驗證,您需要覆蓋Serializer的validate(self, data)
方法,使用data
參數的值進行驗證(這是作為驗證的dict
提供的序列化程序狀態)然后引發ValidationError
如果有的話是錯的。
如果需要為特定字段引發錯誤,則可以將字典作為參數傳遞給ValidationError
構造函數:
raise ValidationError({'yourfield': ['Your message']})
我正在使用幾個mixin來改變現場 。 必需屬性和結果錯誤驗證消息 由DRF自動生成
PerFieldMixin
class ConditionalRequiredPerFieldMixin:
"""Allows to use serializer methods to allow change field is required or not"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name, field in self.fields.items():
method_name = f'is_{field_name}_required'
if hasattr(self, method_name):
field.required = getattr(self, method_name)()
如何使用PerFieldMixin
class MySerializer(ConditionalRequiredPerFieldMixin, serializers.ModelSerializer):
subject_id = serializers.CharField(max_length=128, min_length=3, required=False)
def is_subject_id_required(self):
study = self.context['study']
return not study.is_community_study
PerActionMixin
class ActionRequiredFieldsMixin:
"""Required fields per DRF action
Example:
PER_ACTION_REQUIRED_FIELDS = {
'update': ['notes']
}
"""
PER_ACTION_REQUIRED_FIELDS = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.context.get('view'):
action = self.context['view'].action
required_fields = (self.PER_ACTION_REQUIRED_FIELDS or {}).get(action)
if required_fields:
for field_name in required_fields:
self.fields[field_name].required = True
如何使用PerActionMixin
看到docstrings,for action == update(即PUT請求) - 將需要字段“notes”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.