Search code examples
pythondjangodjango-south

"Person.user" must be a "User" instance


I am writing a small data migration to create UserProfiles for existing Django users who dont have UserProfiles.

def forwards(self, orm):
    "Write your forwards methods here."
    for user in User.objects.all():
        try:
            person = user.get_profile()
        except:
            newperson = orm.Person(user=user)
            newperson.save()

but I keep getting

"Person.user" must be a "User" instance

what am I doing wrong?


Solution

  • When writing migrations in South you don't have to use the models classes directly, but the frozen ones. In the example above, you're likely trying to assign a current User object to a frozen Person one. The frozen Person objects expects a frozen User object.

    You need to rewrite it as follows:

    def forwards(self, orm):
        "Write your forwards methods here."
        for user in orm['auth.User'].objects.all():
            try:
                # cannot use user.get_profile() because it is not available in the frozen model
                person = orm.Person.get(user=user)  
            except:
                newperson = orm.Person(user=user)
                newperson.save()
    

    See http://south.readthedocs.org/en/latest/ormfreezing.html#accessing-the-orm

    BTW I advise you not to use a bare except but except SomeException to be more robust.