gpt4 book ai didi

django-forms - Django中cleaned_data和cleaned_data.get的区别

转载 作者:行者123 更新时间:2023-12-03 21:19:28 25 4
gpt4 key购买 nike

我看过一些示例代码,例如:

    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() 基本上是从 dictionary 中获取元素的快捷方式.我通常使用 .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'

关于django-forms - Django中cleaned_data和cleaned_data.get的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7592552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com