在Django中的clean_data和cleaning_data.get之间的区别 [英] Difference between cleaned_data and cleaned_data.get in Django
本文介绍了在Django中的clean_data和cleaning_data.get之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经看到一些示例代码,如:
I've seen some samples codes like:
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
两者有什么区别?
推荐答案
.get()
基本上是将元素从字典。我通常使用 .get()
,当我不确定字典中的条目是否会在那里。例如:
.get()
is basically a shortcut for getting an element out of a dictionary. I usually use .get()
when I'm not certain if the entry in the dictionary will be there. For example:
>>> 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'
这篇关于在Django中的clean_data和cleaning_data.get之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文