Search code examples
pythondjangoforeign-keysdjango-south

Migration issues when adding ForeignKey to model


I currently have a site which hosts apps and has a database of users. Now I want to connect the two so Apps can have authors (i.e. the users)

Update: A few more pertinent details added below and I'm using django-registration.

Following this as well as the Django docs, I started by adding the author line to my apps model:

from django.contrib.auth.models import User

class App(models.Model):
    name = models.CharField(max_length=200)
    ...
    author = models.ForeignKey(User)

However, when I visit my apps from django admin I get the error DatabaseError at /admin/apps/app/ ...no such column: apps_app.author_id

There are obviously more steps I need to do for this feature, but I'm curious why this simple addition is throwing an error.

I'm using South for migration and ran

./manage.py schemamigration apps --auto

For the one-off value, I set it to "zero" since it expects an int()

./manage.py migrate apps

This didn't work so I did

./manage.py migrate apps --fake

Then the previous command again, no --fake.

Also, per the linked SO question, am I supposed to also create class User(User) in apps/models.py?

Update 2 I just created a new django app (with .manage.py startapp... not to be confused with my "app" object). I went through the steps of creating adding this foreign key and it worked fine. My only conclusion from this is that it must be a South migration issue, and not actually anything wrong with my code.


Solution

  • I've tried this both on my local and stage and this is the best solution I could come up with.

    Because, for some reason, South does not "see" that the author column needs to be added to the apps table, there is a manual schema migration option with the --add-field flag.

    I did:

    /manage.py schemamigration apps --add-field app.author
    

    Then

    ./manage.py migrate apps
    

    If that last one doesn't work, try

    ./manage.py migrate apps --fake 000x
    

    where 000x is the migration number. You can get this from the output of the first step.

    Then restart and it should be fixed. I've been doing this over and over and found I got the most success when I was most specific with South. I would recommend specifying the migration number each time. The migration number carries the directions for that specific change and should directly apply the database transformation.