数据迁移期间的 Django-south ValueError

标签 django foreign-keys django-south data-migration

我正在对使用 Django 构建的系统进行一些更新,现在我在南数据迁移方面遇到了一些麻烦。

我有一个 Cargo 模型,它有一个指向 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 和 Company 相关,如下所示:

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

我创建并运行了一个 schemamigration 以将公司字段添加到 Cargo,然后我创建了一个数据迁移,以便我可以填充我所有 cargo 的公司字段。我想到的是这个:

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 和 South 0.7.3

编辑:如下所述,UserProfileCompany 模型位于 accounts 模块中,并且 Cargocargo 中。所以,简而言之,我有 accounts.UserProfileaccounts.Companycargo.Cargo

最佳答案

您使用的模型版本可能不匹配,因为您是直接导入的:

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()

关于数据迁移期间的 Django-south ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17599895/

相关文章:

mysql - 字段 'foreign key' 没有默认值

python - django + 南 + python : strange behavior when using a text string received as a parameter in a function

django - 重置南部的迁移会导致 'table already exists'

python - 属性错误: 'thread._local' object has no attribute 'browser'

django - Heroku/Django : Could not import user-defined GEOMETRY_BACKEND "geos"

另一个模型上的 Django 管理相关字段

sql - 更改具有外键的表(sql server)中的记录?

django - “讨厌的 “Table ' my_table'已经存在”在Django-South中

Django如何在使用runserver时打印数据

Django-Haystack 使用带有 IAM 凭证的 Amazon Elasticsearch 托管