Django中cleaned_data与cleaned_data.get的区别
我见过一些示例代码,比如:
def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationError("Not enough words!")
return message
还有一些例子,比如:
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
...
self.check_for_test_cookie()
return self.cleaned_data
这两者之间有什么区别呢?
2 个回答
5
cleaned_data 是一个 Python 字典,你可以通过以下方式来获取它的值:
在方括号 [ ] 中指定键:
self.cleaned_data[‘field’]
使用 get() 方法:
self.cleaned_data.get(‘field’)
在 Django 中,cleaned_data 和 cleaned_data.get 的区别在于,如果字典中没有这个键,self.cleaned_data[‘field’]
会报一个 KeyError 错误,而 self.cleaned_data.get(‘field’)
则会返回 None,也就是什么都没有。
32
.get()
是从一个 字典 中获取元素的一个简便方法。通常在我不确定字典里是否有某个条目时,我会使用 .get()
。比如:
>>> cleaned_data = {'username': "bob", 'password': "secret"}
>>> cleaned_data['username']
'bob'
>>> cleaned_data.get('username')
'bob'
>>> cleaned_data['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'foo'
>>> cleaned_data.get('foo') # No exception, just get nothing back.
>>> cleaned_data.get('foo', "Sane Default")
'Sane Default'