Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST API 'get' function

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?

like image 220
Hudson Worden Avatar asked Dec 08 '22 03:12

Hudson Worden


2 Answers

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

like image 132
Wouter Klein Heerenbrink Avatar answered Dec 27 '22 20:12

Wouter Klein Heerenbrink


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.

like image 43
Animesh Sharma Avatar answered Dec 27 '22 22:12

Animesh Sharma