I'm writing a Django view that sometimes gets data from the database, and sometimes from an external API.
When it comes from the database, it is a Django model instance. Attributes must be accessed with dot notation.
Coming from the API, the data is a dictionary and is accessed through subscript notation.
In either case, some processing is done on the data.
I'd like to avoid
if from_DB:
item.image_url='http://example.com/{0}'.format(item.image_id)
else:
item['image_url']='http://example.com/{0}'.format(item['image_id'])
I'm trying to find a more elegant, DRY way to do this.
Is there a way to get/set by key that works on either dictionaries or objects?
You could use a Bunch class, which transforms the dictionary into something that accepts dot notation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With