Is it possible to pass a dictionary on django models at creation?

Is it possible to do something similar with list , dictionary or something else?

 data_dict = { 'title' : 'awesome title', 'body' : 'great body of text', } Model.objects.create(data_dict) 

Even better if I can extend this:

 Model.objects.create(data_dict, extra='hello', extra2='world') 
+100
python dictionary django django-models django-queryset
Oct. 15 '09 at 10:41
source share
2 answers

If title and body are fields in your model, then you can deliver keyword arguments in the 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 should be the last argument. Again, extra and extra2 should be fields in the model.

 m2 =MyModel(extra='hello', extra2='world', **data_dict) m2.save() 
+181
Oct. 15 '09 at 10:49
source share
β€” -

The answer is directly to the question, but I find that this code helped me create voice recorders that retain the correct answer well. Type conversions are required if this data is exported to json.

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 ) 
+1
01 Oct '15 at 23:36
source share



All Articles