Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass a dictionary with extraneous elements to a Django object.create method?

I am aware that when using MyModel.objects.create in Django, it is possible to pass in a dictionary with keys which correspond to the model fields in MyModel. This is explained in another question here: Can a dictionary be passed to django models on create?

However, I am trying to pass in a dictionary which has more keys than there are model fields - in other words, some of the keys are not used in the creation of the object. Is it possible to do this in some way? For example:

data_dict = {
    'key1': value1,
    'key2': value2,
    'key3': value3,
}

class MyModel(models.Model):
    key1 = models.SomeField()
    key2 = models.SomeField()

m = MyModel.objects.create(**data_dict)

When I try this, I get an error telling me that "'key3' is an invalid keyword argument for this function". Am I passing the dictionary in incorrectly? Is there a different way to pass it to the model that means the model doesn't have to use all of the arguments? Or will I simply have to specify each field manually like this:

m = MyModel.objects.create(
    key1 = data_dict['key1'],
    key2 = data_dict['key2'],
)
like image 367
Jonathan Evans Avatar asked May 29 '12 11:05

Jonathan Evans


1 Answers

You can filter, then pass your dictionary this way:

MyModel.objects.create(**{key: value for key, value in data_dict.iteritems() if key in MyModel._meta.get_all_field_names()}).

like image 160
kosii Avatar answered Oct 17 '22 20:10

kosii