Question

I'm making some updates on system built with Django, and now i'm having some trouble with a south datamigration.

I have a model Cargo, which has a Foreign Key to auth.User, and now i want to add a Foreign Key to another model(Company), that is related to the 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
    )

I also have a UserProfile model, which relates to auth.User and Company, like below:

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

I created and ran a schemamigration to add the company field to Cargo, and then i created a datamigration, so that i could fill the company field of all my cargos. What i came up with was this:

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

But when i try to run it, I get the following error:

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

But as you can see in the models above, both fields are of the same kind... Can anyone give me a light with this? I'm on Django 1.3.1 and South 0.7.3

EDIT: As asked below, the UserProfile and Company models are in an accounts module, and Cargo is in a cargo. So, putting it short, i have accounts.UserProfile, accounts.Company and cargo.Cargo

Was it helpful?

Solution

There may be a mismatch between the model versions that you are using, because you imported directly:

from cargobr.apps.accounts.models import UserProfile

Instead, try referencing that model using orm in your migration.

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top