[django]Django model中数据批量导入bulk_create()

时间:2022-11-17 06:44:20

参考: https://www.cnblogs.com/ccorz/p/Django-model-zhong-shu-ju-pi-liang-dao-rubulkcreat.html

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "toupiao.settings")

import django

django.setup()

## 方法1: 串行创建
# def main():
# from app03.models import Question
# f = open('db.db')
# for line in f:
# Question.objects.create(question_text=line)
# f.close()
#
#
# main() ## 方法2: 并行创建bulk_create
def main2():
from app03.models import Question
f = open('db.db')
question_list = []
for line in f:
quesiton = Question(question_text=line)
question_list.append(quesiton)
f.close()
Question.objects.bulk_create(question_list) main2()

tips: 使用get_or_create()可以防止插入数据重复

[django]Django model中数据批量导入bulk_create()