[Django]-What is different between `request.data['param-name'] ` or `request.data.get('param-name')` in Django

6👍

If you perform a request.data['key'] call, behind the curtains, Python will call the __getitem__ function of request.data. We can read the documentation and see:

QueryDict.__getitem__(key)

Returns the value for the given key. If the key has more than one
value, it returns the last value. Raises
django.utils.datastructures.MultiValueDictKeyError if the key does
not exist
. (This is a subclass of Python’s standard KeyError, so
you can stick to catching KeyError.)

Whereas if you perform a request.data.get('key'), it will call the.get(..)` function, and we see in the documentantation:

QueryDict.get(key, default=None)

Uses the same logic as __getitem__(), with a hook for returning a
default
value if the key doesn’t exist.

So it means that if the key does not exists, .get(..) will return None, in case you did not provide a default, or it will return the given default if you query with request.data.get('key', somedefault).

Typically the latter is used in case the value is optional, and you want to reduce the amount of code to check if the key exists.

2👍

Yes both of them will give you the same results, but what makes them different is the way they retrieve the data for a given key. For this you need to understand how dictionaries in python works, lets define a dict:

>>> kwarg = {'name': 'John'}
>>> kwarg['name']
'John'
>>> kwarg['age']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age'
>>>
>>> kwarg.get('age', 25)
25

In the above example in the first method the key has to be present whereas in second case I can define a default value if the key is not found.

Leave a comment