Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Access model as dictionary

I have data in a python dictionary that I'd like to store in a model instance. For example, my dictionary might look like

data = { 'date': '6/17/09', 'name': 'something', 'action': 'something' }

And my model might look like:

class Something(models.Model):
    date = models.DateField()
    name = models.CharField()
    action = models.CharField()

I'm looking for a clean way to do something like this:

s = Something()
for k in data:
    s[k] = data[k]

[Update] Shortly after posting this I realized I probably just want to use the Django (de)serializer framework with the 'python' serializer. Ayman's answer is quite nice as well, let me think about which will work better.

like image 958
Parand Avatar asked Dec 29 '22 20:12

Parand


1 Answers

You can use argument unpacking:

data = {'date': '6/17/09', 'name': 'something', 'action': 'something'}
s = Something(**data)

This is equivalent to:

s = Something(date='6/17/09', name='something', action='something')
like image 60
Ayman Hourieh Avatar answered Jan 04 '23 14:01

Ayman Hourieh