2013-07-11 46 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