views:

212

answers:

1

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.

+3  A: 

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')
Ayman Hourieh
Nice, that's even more obvious.
Parand