我對使用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南
編輯:如下要求,該UserProfile
和Company
模型是一個accounts
模塊中,並Cargo
處於cargo
。所以,把它短,我有accounts.UserProfile
,accounts.Company
和cargo.Cargo
什麼模塊是'UserProfile'中的?看起來你直接從那裏引用'Company',但在'Cargo'中使用''accounts.Company''。你有兩個同名的班級嗎? – voithos
'UserProfile'和'Company'都在'accounts'應用中,'Cargo'在'cargo'應用中,這就是爲什麼我直接在'UserProfile'中引用'Company',而不是'Cargo' – Thiago
這可能是由於你直接導入了'UserProfile'。根據[數據遷移的南教程](http://south.readthedocs.org/en/latest/tutorial/part3.html),從不同應用程序訪問模型的一種方法是使用'orm ['someapp.SomeModel'] ',所以在你的情況下,你可以做'orm'''accounts.UserProfile']'而不是'從貨物...'。該機制確保模型的實例與創建數據遷移時的實例相同。 – voithos