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

2024/10/12 4:29:20

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'],
)
Answer

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()}).

https://en.xdnf.cn/q/69690.html

Related Q&A

When should I use varargs in designing a Python API?

Is there a good rule of thumb as to when you should prefer varargs function signatures in your API over passing an iterable to a function? ("varargs" being short for "variadic" or …

PyPDF2 wont extract all text from PDF

Im trying to extract text from a PDF (https://www.sec.gov/litigation/admin/2015/34-76574.pdf) using PyPDF2, and the only result Im getting is the following string:bHere is my code:import PyPDF2 import …

Python 3.4 decode bytes

I am trying to write a file in python, and I cant find a way to decode a byte object before writing the file, basically, I am trying to decode this bytes string:Les \xc3\x83\xc2\xa9vad\xc3\x83\xc2\xa9s…

No module named unusual_prefix_*

I tried to run the Python Operator Example in my Airflow installation. The installation has deployed webserver, scheduler and worker on the same machine and runs with no complaints for all non-PytohnOp…

Python: Variables are still accessible if defined in try or if? [duplicate]

This question already has answers here:Short description of the scoping rules(9 answers)Closed last year.Im a Python beginner and I am from C/C++ background. Im using Python 2.7.I read this article: A …

Networkx Traveling Salesman Problem (TSP)

I would like to know if there is a function in NetworkX to solve the TSP? I can not find it. Am I missing something? I know its an NP hard problem but there should be some approximate solutions right

Comparing dateutil.relativedelta

Im trying to do a > comparison between two relativedeltas: if(relativedelta(current_date, last_activity_date) > relativedelta(minutes=15)):Here is the output from the debugger window in Eclipse:O…

Python. Argparser. Removing not-needed arguments

I am parsing some command-line arguments, and most of them need to be passed to a method, but not all.parser = argparse.ArgumentParser() parser.add_argument("-d", "--dir", help = &q…

Where can I find some hello world-simple Beautiful Soup examples?

Id like to do a very simple replacement using Beautiful Soup. Lets say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to …

Difference between isnumeric and isdecimal in Python

What is the difference between isnumeric and isdecimal functions for strings ( https://www.tutorialspoint.com/python3/python_strings.htm )? They seem to give identical results: >>> "1234…