Can a dictionary be passed to django models on create?

后端 未结 2 462
渐次进展
渐次进展 2020-12-04 05:42

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

data_dict = {
    \'title\' : \'awesome t         


        
2条回答
  •  独厮守ぢ
    2020-12-04 06:30

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

提交回复
热议问题