Difference between cleaned_data and cleaned_data.get in Django

后端 未结 2 482
清歌不尽
清歌不尽 2021-02-02 15:25

I\'ve seen some samples codes like:

    def clean_message(self):
    message = self.cleaned_data[\'message\']
    num_words = len(message.split())
    if num_wor         


        
2条回答
  •  耶瑟儿~
    2021-02-02 15:58

    .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 "", line 1, in 
        KeyError: 'foo'
    >>> cleaned_data.get('foo')  # No exception, just get nothing back.
    >>> cleaned_data.get('foo', "Sane Default")
    'Sane Default'
    

提交回复
热议问题