Create Django Model from a list of dictionaries

Pavan Skipo :

I want to create a model from a list of dictionaries (i.e) it should be similar to this query

result = MyModal.objects.all()

I know that we can create an instance of a model like this MyModal(**data_dict), I want something similar so i can pass in a list of dictionaries.

data_list = [{name: 'abc'}, {name: 'xyz'}]
# result = "Logic to create instance for 2 objects"

I want to serialize this data and then pass it to a REST API response.

Ping me in comments if more explanation is needed.

neverwalkaloner :

You can use bulk_create to perform multiple create in sigle query:

data_list = [{name: 'abc'}, {name: 'xyz'}]
obj_list = [MyModal(**data_dict) for data_dict in data_list]
objs = MyModal.objects.bulk_create(obj_list)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12099&siteId=1