Reputation: 106300
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.
Upvotes: 4
Views: 2003
Reputation: 137156
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')
Upvotes: 10