简体   繁体   中英

Error creating table with foreign key constraint using SQLAlchemy-Migrate

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'

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM