【发布时间】:2015-02-16 17:50:56
【问题描述】:
我有一个定义了模型 (Person) 的 django 应用程序,并且我还有一些没有定义任何模型的数据库(其中有一个表 Appointment)(不打算连接到 django应用程序)。
我需要将Appointment 表中的一些数据移动到Person,以便 People 表需要反映 Appointment 表的所有信息。之所以这样,是因为需要将多个独立的数据库(例如 Appointment)复制到 Person 表中(因此我不想对其设置方式进行任何架构更改)。
这是我现在要做的:
res = sourcedb.fetchall() # from Appointment Table
for myrecord in res:
try:
existingrecord = Person.objects.filter(vendorid = myrecord[12], office = myoffice)[0]
except:
existingrecord = Person(vendorid = myrecord[12], office = myoffice)
existingrecord.firstname = myrecord[0]
existingrecord.midname = myrecord[1]
existingrecord.lastname = myrecord[2]
existingrecord.address1 = myrecord[3]
existingrecord.address2 = myrecord[4]
existingrecord.save()
问题是这太慢了(20K 条记录大约需要 8 分钟)。我该怎么做才能加快速度?
我考虑过以下方法:
1. bulk_create: 不能用这个,因为我有时要更新。
2。 delete all 然后 bulk_create 由于 Person 模型对其他事物的依赖,所以我无法删除 Person 模型中的记录。
3。 INSERT ... ON DUPLICATE KEY UPDATE: 无法执行此操作,因为 Person 表的 PK 与 Appointment 表 PK(主键)不同。约会 PK 被复制到人员表中。如果有办法检查两个重复的键,我认为这种方法会起作用。
【问题讨论】:
标签: python mysql django orm mysql-python