Bulk create model objects in django

后端 未结 8 2037
执笔经年
执笔经年 2020-12-13 05:17

I have a lot of objects to save in database, and so I want to create Model instances with that.

With django, I can create all the models instances, with MyMode

8条回答
  •  渐次进展
    2020-12-13 06:07

    Here is how to bulk-create entities from column-separated file, leaving aside all unquoting and un-escaping routines:

    SomeModel(Model):
        @classmethod
        def from_file(model, file_obj, headers, delimiter):
            model.objects.bulk_create([
                model(**dict(zip(headers, line.split(delimiter))))
                for line in file_obj],
                batch_size=None)
    

提交回复
热议问题