views:

325

answers:

2

Is is possible to do something similar to this with a list, dictionary or something else even?

data_dict = {
    'title' : 'awesome title',
    'body' : 'great body of text',
}
Model.objects.create(data_dict)

Even better if I can extend it

Model.objects.create(data_dict, extra='hello', extra2='world)
+12  A: 

If title and body are fields in your model, then you can deliver the keyword arguments in your dictionary using the ** operator.

Assuming your model is called MyModel:

# create instance of model
m = MyModel(**data_dict)
# don't forget to save to database!
m.save()

As for your second question, the dictionary has to be the final argument. Again, extra and extra2 should be fields in the model.

m2 =MyModel(extra='hello', extra2='world', **data_dict)
m2.save()
Alasdair
Thanks, that is exactly what I was looking to do. Also, as a side note just based off your post. You don't have to call the save method when using Model.objects.create(**data_dict). You probably already know this but just a heads up.
clarence
I've not used the `objects.create` method before, so you've taught me something new.
Alasdair
also objects.create returns a pointer to the new model, with a valid pk filled in. This means you can immediately use it to build related models.
Tom Leys
A: 

Hi !!!

The dict key names must be the same of the field in the models ?

Thanks !

fchevitarese
Yes, the keys should match the field names.
Alasdair