【问题标题】:Difference between cleaned_data and cleaned_data.get in DjangoDjango中cleaned_data和cleaned_data.get之间的区别
【发布时间】:2011-09-29 04:47:06
【问题描述】:

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

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

两者有什么区别?

【问题讨论】:

  • 正是我需要的问题(和答案)。我没有遇到过使用 dictionary.get() 因为在我所有的开发过程中我一直使用快捷方式 dictionary[key]

标签: django-forms


【解决方案1】:

.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 表单的上下文中,最后一行代码意味着您可以通过这种方式为表单字段提供默认值。但除非我遗漏了什么,否则这是行不通的,至少在 Django 1.8 中不行。如果客户端未设置,则可选 (required=False) 表单字段包含空字符串 ''
  • @BobStein-VisiBone 我明白为什么这可能会令人困惑。我把它包括在内是因为我的回答更关注cleaned_data 是“只是一本字典”。但是,如果您有一个可选字段,则字典中的条目将存在,get() 将不会使用“Sane Default”。但是,如果您有一个可能存在的字段,那么字典中的条目可能存在也可能不存在。因此需要谨慎,在我的情况下,使用get() 不会引发异常。
【解决方案2】:

cleaned_data 是一个 Python 字典,您可以通过以下方式访问其值:

指定 [ ] 之间的键:

 self.cleaned_data[‘field’]

使用 get() 方法:

self.cleaned_data.get(‘field’)

Django 中cleaned_data 和cleaned_data.get 的区别在于,如果字典中不存在key,self.cleaned_data[‘field’] 会引发KeyError,而self.cleaned_data.get(‘field’) 会返回None。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 2017-08-25
    • 2023-03-06
    • 2013-12-15
    • 2021-08-20
    • 1970-01-01
    • 2021-05-19
    • 2011-03-14
    相关资源
    最近更新 更多