在我的DRF模型中,我有下一个字段:
myfield = ArrayField(
models.CharField(max_length=7, blank=True, null=True),
blank=True,
null=True
)
并且在序列化器中我正在编写用于验证此myfield的函数:
def validate_myfield(self, value): # validate only for this myfield (value = field value from request)
**some validations**
return value
但如果在请求字段myfield = "string"/integer_value
或其他内容中,我会从基本字段验证(来自其他序列化程序)中收到错误:Expected a list of items but got type \"int\".
。
如何在myfield验证之前拦截此错误(如果在请求字段中没有字符串数组,验证没有启动)并打印我的错误消息?
答案 0 :(得分:0)
如果你想检查类类型类型.isinstance是非常有用的
def validate_myfield(self, value): # validate only for this myfield (value = field value from request)
assert isinstance(value,list )
# Your code here when the assertion pass
to excluse string,and it
assert not isinstance(value,(int,str))
return value