django Framework model orM Using Dictionary as Parameter to Save Data

  • 2021-07-01 07:44:24
  • OfStack

In this paper, an example of django framework model orM using dictionaries as parameters to save data. Share it for your reference, as follows:

Suppose you have a dictionary, which already has all the relevant information. Now you want to use this dictionary as a parameter, combine it with django model, and save data with a small amount of code. What is the simple method, such as model with the following definition:


from django.db import models
class MyModel(models.Model):
  title=models.CharField(max_length=250)
  body= models.CharField(max_length=1000)
  ....

There is a dictionary:


data_dict = {
  'title' : 'awesome title',
  'body' : 'great body of text',
}

If you follow the conventional practice, you may save the data in the following ways:


mymodel = MyModel()
mymodel.title = data_dict['title']
mymodel.bdy = data_dict['body']
mymodel.save()

Or so


mymodel = MyModel(title=data_dict['title'],body=data_dict['body'])
mymodel.save()

Actually, it's one kind. Get data from dict.

In fact, there is a simpler way to pass in this dict data directly, but the premise is: the key field 1 in the dictionary data must correspond to field defined in model, otherwise an error will be reported. But in fact, when encapsulating dict data, it can be completely corresponding. Save as follows


mymodel = MyModel(**data_dict)
mymodel.save()

If there are 1 other extension fields, you can also add them, but note that **data_dict must be at the end:


mymodel =MyModel(extra='hello', extra2='world', **data_dict)
mymodel .save()

You can also do this:


MyModel.objects.create(**data_dict)

This only implements django, model, saves dict, and can be extended

Update 2013-01-04: In a recent article, I found that if you want to update an model with the dictionary dict as a parameter, the method is as follows:


mymodel=MyModel.objects.get(pk=pk)#.... Find only 1 Adj. 1 A , Self-modification 
mymodel.__dict__.update(data_dict )
mymodel.save()

Of course, it is also useful to implement updates in the following ways:


MyModel.objects.filter(pk=pk).update(**data_dict )

I hope this article is helpful to the Python programming based on Django framework.


Related articles: