Request.POST.get ('sth') vs request.POST ['sth'] - difference?

What's the difference between

request.POST.get('sth') 

and

 request.POST['sth'] 

I did not find a similar question, both work the same way for me, suppose I can use them separately, but maybe I'm wrong, so I ask. Any ideas?

+53
django
Sep 20 '12 at 18:18
source share
2 answers

request.POST['sth'] throws a KeyError exception if 'sth' not in request.POST .

request.POST.get('sth') will return None if 'sth' not in request.POST .

In addition, .get allows you to provide an additional default parameter value, which is returned if the key is not in the dictionary. For example, request.POST.get('sth', 'mydefaultvalue')

This is the behavior of any python dictionary and does not apply to request.POST .





These two fragments are functionally identical:

The first fragment:

 try: x = request.POST['sth'] except KeyError: x = None 


Second snippet:

 x = request.POST.get('sth') 





These two fragments are functionally identical:

The first fragment:

 try: x = request.POST['sth'] except KeyError: x = -1 


Second snippet:

 x = request.POST.get('sth', -1) 





These two fragments are functionally identical:

The first fragment:

 if 'sth' in request.POST: x = request.POST['sth'] else: x = -1 


Second snippet:

 x = request.POST.get('sth', -1) 
+123
Sep 20 '12 at 18:20
source share

The main difference between accessible normal dictionaries and access to it with .get () is that

Using something like request.POST['sth'] , a key error occurs if ket 'sth' does not exist. But using get () method dictionaries will also provide better error handling.

 request.POST.get('sth') 

will return none, the key "sth does not exist" and also by providing the second parameter get () will return the default value with it.

 data = request.POST.get('sth','my_default_value') 

If the `sth 'key does not exist, the value in the data will be my_default_value . This is the advantage of using the get () method over normal dictionaries.

0
03 Oct '17 at 17:37 on
source share



All Articles