286๐
โ
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
1๐
For any model DummyModel
you can use DummyModel.objects.create(**data_dict)
. Does not require save after the create.
๐คcodehia
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-Chained method calls indentation style in Python
- [Django]-Why am I getting this error in Django?
0๐
Not directly an answer to the question, but I find this code helped me create the dicts that save nicely into the correct answer. The type conversions made are required if this data will be exported to json.
I hope this helps:
#mod is a django database model instance
def toDict( mod ):
import datetime
from decimal import Decimal
import re
#Go through the object, load in the objects we want
obj = {}
for key in mod.__dict__:
if re.search('^_', key):
continue
#Copy my data
if isinstance( mod.__dict__[key], datetime.datetime ):
obj[key] = int(calendar.timegm( ts.utctimetuple(mod.__dict__[key])))
elif isinstance( mod.__dict__[key], Decimal ):
obj[key] = float( mod.__dict__[key] )
else:
obj[key] = mod.__dict__[key]
return obj
def toCsv( mod, fields, delim=',' ):
import datetime
from decimal import Decimal
#Dump the items
raw = []
for key in fields:
if key not in mod.__dict__:
continue
#Copy my data
if isinstance( mod.__dict__[key], datetime.datetime ):
raw.append( str(calendar.timegm( ts.utctimetuple(mod.__dict__[key]))) )
elif isinstance( mod.__dict__[key], Decimal ):
raw.append( str(float( mod.__dict__[key] )))
else:
raw.append( str(mod.__dict__[key]) )
return delim.join( raw )
๐คLuke Dupin
- [Django]-Django values_list vs values
- [Django]-How to test "render to template" functions in django? (TDD)
- [Django]-How can I check the size of a collection within a Django template?
Source:stackexchange.com