rimraf
rimraf

Reputation: 4126

Django object create with one or more items (dynamically)

Is there a way to use model.objects.create(<dict>)

Say my model has many optional fields. I would like to just pass a dict with whatever is there instead of manually assigning each field like:

Model.objects.create(thing=data['prop'],...)

Here's a more clear (pseudo code) example: Say i've got a model thats got

class MyModel(models.Model):
  thing=models... // all these fields null=True, blank=True
  another=...
  possibly_another=...
  ...

data = {'thing': 'value for thing', 'another': 'value for another'}

MyModel.objects.create(data)

In this example my data doesn't have possibly_another and maybe more. I have tried doing this but i'm getting a positional arg error... I did some google-foo and i must not have my terms correct. (I'm more of a node/js guy)

Is there a way to just pass the dict and have the create method sort out what's there and not?

Upvotes: 2

Views: 186

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can perform dictionary unpacking by using two consecutive asterisks (**):

MyModel.objects.create(**data)

If the dictionary contains for example data = { 'a': 4, 'b': 2 }, if you perform dictionary unpacking f(**data), it will call the function with f(a=4, b=2).

Note that for the missing values, you should have default=... parameters in these fields.

Upvotes: 2

Related Questions