我正在python中构建一个应用程序。我正在使用sqlalchemy-migrate来跟踪我的数据库架构。我有一个表user_category,它有两列:id和name。我正在尝试使用user_category表的外键创建一个用户表。我创建用户表的更改脚本如下:
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()
当我运行'manage.py test'时,我得到了错误:
sqlalchemy.exc.NoReferencedColumnError: Could not create ForeignKey 'user_catego
ry.id' on table 'user': table 'user_category' has no column named 'id'
答案 0 :(得分:5)
可以告诉SQLAlchemy从数据库中自动加载表结构,而不是复制粘贴user_category
表的定义:
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()
对不起,迟到的答案:)
答案 1 :(得分:2)
您声称您的“user_category”表具有名称和ID。 “user_category”的定义根本不包含任何列:)