我正在对用Django构建的系统进行一些更新,现在我在南方数据迁移方面遇到了一些麻烦。
我有一个模型货,它有一个外键到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
)我还有一个UserProfile模型,它与auth.User和公司有关,如下所示:
class UserProfile(models.Model):
company = models.ForeignKey(
Company,
verbose_name='Empresa',
null=True
)
user = models.OneToOneField('auth.User')我创建并运行了一个模式迁移来将公司字段添加到货物中,然后我创建了一个数据迁移,这样我就可以填充我所有货物的公司字段。我想出来的是:
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
发布于 2013-07-11 18:02:04
您使用的模型版本可能不匹配,因为您直接导入了:
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()https://stackoverflow.com/questions/17599895
复制相似问题