【问题标题】:Migrating data with south to a new model not working将数据与南迁移到新模型不起作用
【发布时间】:2012-02-01 16:08:55
【问题描述】:

我有一个要转换为具体模型的抽象模型。我已成功使用 south 更改架构,但无法使用数据迁移。

我的初始状态是:

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, \
                                related_name='profile')
    class Meta:
        abstract=True
class SpecificProfile(UserProfile):
    url = models.URLField()

我的新状态是:

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, \
                                related_name='profile')
class SpecificProfile(UserProfile):
    user_profile = models.OneToOneField(UserProfile, parent_link=True)
    url = models.URLField()

我的架构迁移是:

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Renaming field 'SpecProfile.user_profile'
        db.rename_column('specificprofile', 'user_id', 'user_profile_id')

        # Adding model 'UserProfile'
        db.create_table('userprofile', (
            ('user', self.gf('django.db.models.fields.related.OneToOneField')(related_name='profile', unique=True, primary_key=True, to=orm['auth.User'])),
        ))
        db.send_create_signal('myapp', ['UserProfile'])

我编辑了由 south 生成的文件,以便重命名 SpecificProfile 中的一个字段

现在,在数据迁移过程中,我想为每个SpecificProfile 创建一个UserProfile 条目,并将UserProfile.user_id 分配给SpecificProfile.user_profile_id

所以,我的数据向前迁移是:

class Migration(DataMigration):

    def forwards(self, orm):
        for spec in orm.SpecificProfile.objects.all():
            user_profile = orm.UserProfile()
            user_profile.user_id = spec.user_profile_id
            user_profile.save()

脚本运行没有错误,但不会在 UserProfile 表中创建任何新条目。 我应该使用UserProfile() 而不是orm.UserProfile()

有什么想法吗?

【问题讨论】:

    标签: django data-migration django-south


    【解决方案1】:

    SpecificProfile.user_profile_id 以前不存在,因此它没有要迁移的数据。您真正想要做的是将user_profile.user 设置为spec.user,然后将spec.user_profile 设置为user_profile

     def forwards(self, orm):
        for spec in orm.SpecificProfile.objects.all():
            user_profile = orm.UserProfile()
            user_profile.user_id = spec.user_id
            user_profile.save()
    
            # Then,
            spec.user_profile_id = user_profile.id
    

    但是,一旦您完成了初始迁移,我很确定 SpecificProfile.user 不再存在。 South 删除了该字段,因为它现在位于 UserProfile

    【讨论】:

    • SpecificProfile.user_profile_id 应该在架构迁移之后存在,因为我将 SpecificProfile.user_id 重命名为 SpecificProfile.user_profile_id。检查我上面的架构迁移代码。此重命名工作正常。我测试了你的代码,以防万一,但它也没有工作,可能是你指出的原因。
    • 我的问题是 orm.SpecificProfile.objects.all() 返回一个空列表
    猜你喜欢
    • 2012-09-08
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多