Error creating table with foreign key constraint using SQLAlchemy-Migrate

3.4k views Asked by At

I'm building an app in python. I'm using sqlalchemy-migrate to track my database schema. I have a table, user_category, which has two columns: id and name. I'm trying to create a user table with a foreign key to the user_category table. My change script for creating the user table is as follows:

from sqlalchemy import *
from migrate import *
from migrate.changeset import *

meta = MetaData()
user_category = Table('user_category', meta)

user = Table('user', meta,
    Column('id', Integer, primary_key=True),
    Column('email', String(255)),
    Column('first_name', String(40)),
    Column('surname', String(40)),
    Column('password', String(255)),
    Column('user_category', Integer, ForeignKey("user_category.id")),
)

def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind migrate_engine
    # to your metadata
    meta.bind = migrate_engine
    user.create()

def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    meta.bind = migrate_engine
    user.drop()

When I run 'manage.py test' I get and error:

sqlalchemy.exc.NoReferencedColumnError: Could not create ForeignKey 'user_catego
ry.id' on table 'user': table 'user_category' has no column named 'id'
2

There are 2 answers

1
iElectric On BEST ANSWER

You claim your "user_category" table has name and id. Definition of "user_category" contains no columns at all :)

2
Sergey On

Instead of copy-pasting the definition of user_category table it is possible to tell SQLAlchemy to auto-load the table structure from the database:

from sqlalchemy import *
from migrate import *
from migrate.changeset import *

meta = MetaData()

user = Table('user', meta,
    Column('id', Integer, primary_key=True),
    Column('email', String(255)),
    Column('first_name', String(40)),
    Column('surname', String(40)),
    Column('password', String(255)),
    Column('user_category', Integer, ForeignKey("user_category.id")),
)

def upgrade(migrate_engine):
    _t = sa.Table('user_category', meta, autoload=True)
    meta.bind = migrate_engine
    user.create()

Sorry for the late answer :)