2012-02-01 58 views
0

我有一個抽象模型,我將其轉換爲具體模型。我成功使用南來更改架構,但我無法使用數據遷移。向南遷移數據到新模型不起作用

我的初始狀態是:

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']) 

我編輯由南生成的文件以在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()而不是orm.UserProfile()

任何想法?

回答

0

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

+0

SpecificProfile.user_profile_id應該在schemamigration之後存在,因爲我將SpecificProfile.user_id重命名爲SpecificProfile.user_profile_id。查看我上面的schemamigration代碼。這個重命名工作正常。 我測試了你的代碼,以防萬一,但它也沒有工作,可能是你指出的原因。 – duduklein 2012-02-01 18:02:47

+0

我的問題是,orm.SpecificProfile.objects.all()返回一個空列表 – duduklein 2012-02-02 12:06:54