简体   繁体   English

使用SQLAlchemy-Migrate创建具有外键约束的表时出错

[英]Error creating table with foreign key constraint using SQLAlchemy-Migrate

I'm building an app in python. 我在python中构建一个应用程序。 I'm using sqlalchemy-migrate to track my database schema. 我正在使用sqlalchemy-migrate来跟踪我的数据库架构。 I have a table, user_category, which has two columns: id and name. 我有一个表user_category,它有两列:id和name。 I'm trying to create a user table with a foreign key to the user_category table. 我正在尝试使用user_category表的外键创建一个用户表。 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: 当我运行'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'

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: 可以告诉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()

Sorry for the late answer :) 抱歉回复晚了 :)

You claim your "user_category" table has name and id. 您声称您的“user_category”表具有名称和ID。 Definition of "user_category" contains no columns at all :) “user_category”的定义根本不包含任何列:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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