2013-07-11 122 views
3

我對使用Django構建的系統進行了一些更新,現在我在南數據遷移時遇到了一些問題。數據遷移期間的Django-SouthErrorError

我有一個模型貨物,其中有一個外鍵到auth.User,現在我想添加一個外鍵到另一個模型(公司),這是auth.User相關。

class Cargo(models.Model): 
    company = models.ForeignKey(
     'accounts.Company', 
     related_name='cargo_company', 
     verbose_name='empresa', 
     null=True, 
     blank=True 
    ) 

    customer = models.ForeignKey(
     'auth.User', 
     related_name='cargo_customer', 
     verbose_name='embarcador', 
     limit_choices_to={'groups__name': 'customer'}, 
     null=True, 
     blank=True 
    ) 

我也有一個用戶配置模型,它涉及到auth.User和公司,象下面這樣:

class UserProfile(models.Model): 
    company = models.ForeignKey(
     Company, 
     verbose_name='Empresa', 
     null=True 
    ) 
    user = models.OneToOneField('auth.User') 

我創建並運行了一個schemamigration公司字段添加到貨物,然後我創建了一個數據移植,這樣我就可以填滿我所有貨物的公司領域。我想出了是這樣的:

class Migration(DataMigration): 

def forwards(self, orm): 
    try: 
     from cargobr.apps.accounts.models import UserProfile 
    except ImportError: 
     return 

    for cargo in orm['cargo.Cargo'].objects.all(): 
     profile = UserProfile.objects.get(user=cargo.customer) 
     cargo.company = profile.company 
     cargo.save() 

但是,當我嘗試運行它,我得到以下錯誤:

ValueError: Cannot assign "<Company: Thiago Rodrigues>": "Cargo.company" must be a "Company" instance. 

但你可以在上面的模型看,這兩個領域是同一種...任何人都可以給我一個這樣的燈光?我在Django的1.3.1和0.7.3南

編輯:如下要求,該UserProfileCompany模型是一個accounts模塊中,並Cargo處於cargo。所以,把它短,我有accounts.UserProfileaccounts.Companycargo.Cargo

+0

什麼模塊是'UserProfile'中的?看起來你直接從那裏引用'Company',但在'Cargo'中使用''accounts.Company''。你有兩個同名的班級嗎? – voithos

+0

'UserProfile'和'Company'都在'accounts'應用中,'Cargo'在'cargo'應用中,這就是爲什麼我直接在'UserProfile'中引用'Company',而不是'Cargo' – Thiago

+0

這可能是由於你直接導入了'UserProfile'。根據[數據遷移的南教程](http://south.readthedocs.org/en/latest/tutorial/part3.html),從不同應用程序訪問模型的一種方法是使用'orm ['someapp.SomeModel'] ',所以在你的情況下,你可以做'orm'''accounts.UserProfile']'而不是'從貨物...'。該機制確保模型的實例與創建數據遷移時的實例相同。 – voithos

回答

0

有可能是您所使用的模型版本之間的不匹配,因爲你直接輸入:

from cargobr.apps.accounts.models import UserProfile 

相反,嘗試引用使用模型orm在您的遷移。

class Migration(DataMigration): 

def forwards(self, orm): 
    for cargo in orm['cargo.Cargo'].objects.all(): 
     profile = orm['accounts.UserProfile'].objects.get(user=cargo.customer) 
     cargo.company = profile.company 
     cargo.save() 
+1

謝謝!我只需要做一件額外的工作就可以解決這個問題:我必須重新創建數據遷移,這次使用'--freeze accounts'參數來將此模型包含在遷移中。然後它完美的工作! – Thiago

+0

@Thiago:太好了!歡迎來到Stack Exchange! – voithos

+0

乾杯,已經使用了很長一段時間,但最近我開始問問題..希望我將能夠在未來幫助其他人 – Thiago