Django REST API 'get' function

1.8k Views Asked by At

I'm following the tutorial here. I have come across this:

def update(self, instance, validated_data):
      instance.title = validated_data.get('title', instance.title)
      instance.code = validated_data.get('code', instance.code)
      instance.linenos = validated_data.get('linenos', instance.linenos)
      instance.language = validated_data.get('language', instance.language)
      instance.style = validated_data.get('style', instance.style)
      instance.save()
      return instance

This is probably a very simple question, but what is get function here? I'm having trouble finding any documentation about what it is. I understand that there is a get query function, but are these the same functions?

3

There are 3 best solutions below

0
On BEST ANSWER

validated_data is an OrderedDict and OrderedDict.get(key, default) is the method that fetches the value for the given key, returning the default if the key is missing from the dict.

In other words: instance.title = validated_data.get('title', instance.title) will try to fetch title from validated_data but will return the current instance.title if the title key is not present in the validated data.

https://docs.python.org/2/library/collections.html#collections.OrderedDict https://docs.python.org/2/library/stdtypes.html#dict.get

0
On

get is a dictionary method. You pass it a key and it returns the value associated with the key. Optionally, you can also pass it the value you want it to return in case the key is missing from the dictionary. It is not necessary to specify a default value (it returns None is the key is not there), but it makes things clearer, even when you want None.

For example:

d={'ciao':1, 'how':2, 'are':3, 'you':4}
my_val = d.get('how', 10)
print 'my_val =', my_val

outputs

my_val = 2

whereas

my_val = d.get('absent', 10)
print 'my_val =', my_val

outputs

my_val = 10
0
On

get has nothing to do with the REST API.

validated_data is a dictionary. You can extract the value from the dictionary in the following ways.

d = some_dictionary

**Method 1:** a = d[key]
**Method 2:** a = d.get(key,custom_value)

In Method 1, a is assigned a value if key is present in the dictionary d. If key is not present, KeyError is raised.

In Method 2, a is assigned the value of d[key] if key is present in the dictionary else it is assigned the custom_value. The custom_value by default is None. Thus, an exception will not be raised even of the dictionary does not contain the key you are looking for.

In short, Method 2 is the safe method for accessing keys of a dictionary.