我们正在慢慢地从非托管模式转变为托管模式,一次一个外键。目前的情况:
class OldOrg(Model):
pass
class Meta:
managed = False
class OldService(Model):
offered_by = models.ForeignKey(OldOrg)
class Meta:
managed = False
class NewOrg(Model):
org = models.OneToOneKey(OldOrg)
class NewService(Model):
service = OneToOneKey(OldService)
下一步:
class NewService(Model):
service = OneToOneKey(OldService)
offered_by = models.ForeignKey(NewOrg)
使用django的内置迁移系统进行数据迁移时会出现问题。字段OldService.offered_by
不存在,因此我们无法使用该字段访问NewOrg
主键,以便在NewService.offered_by
中使用。
# This works in the shell but not in a migration
for ns in NewService.objects.all():
ns.offered_by = ns.service.offered_by.new_org
在迁移过程中,OldService
也没有字段offered_by_id
。是否有其他方法可以获取OldService
中的数据?
答案 0 :(得分:0)
我找到了解决方案,但我不喜欢它:
在迁移中使用尽可能的原始SQL:
from django.db import connection
def copy_org(apps, schema_editor):
NewService = apps.get_model('myapp', 'NewService')
with connection.cursor() as cursor:
cursor.execute('SELECT id, offered_by FROM myapp_old_service')
old_services = dict(cursor.fetchall())
for ns in NewService.objects.all():
ns.offered_by = old_services[ns.pk]
ns.save()