In Python, you can create a dictionary dict with curly brackets {} , dict() , and dictionary comprehensions.
A dictionary in Python is made up of key-value pairs. In the two sections that follow you will see two ways of creating a dictionary. The first way is by using a set of curly braces, {} , and the second way is by using the built-in dict() function.
By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With