我已将数据的文本文件制成表格,记录的数量太多,无法在数据库中一张一张地上传 有什么方法可以将数据导入到我在模型
中创建的表中答案 0 :(得分:0)
我创建了一个简单的脚本,可能对您来说是一个开始。该脚本将读取一个csv文件并将其存储到数据库中。通过将filename.csv
替换为文件位置,并将YourModel
替换为它代表的实际模型,您应该能够修改它以满足您的需求。您还需要将obj.field1 = line[0]
更改为彼此匹配的代表列和字段。
import csv
# Open the csv file and reads it into a two dimensional List
with open('filename.csv', 'rb') as f:
reader = csv.reader(f)
lines = list(reader)
# Create an empty list of objects of your model
objects = []
# Iterate each record of the csv file
for line in lines:
# Create an empty instance of your model
obj = YourModel()
# Populate the fields of the model based on the record line of your file
obj.field1 = line[0] # The first column
obj.field2 = line[1] # The second column
# Add the model to the list of objects
objects.append(obj)
# Save all objects simultaniously, instead of saving for each line
YourModel.objects.bulk_create(objects)