sqlalchemy - Alembic 不制作复合主键

标签 sqlalchemy alembic

我有一个 SQLAlchemy 模型,例如 -

class UserFavPlace(db.Model):
    # This model stores the feedback from the user whether he has
    # faved a place or not
    __tablename__ = u'user_fav_places'

    id = db.Column(db.Integer, primary_key = True)
    public_place_id = db.Column(db.Integer, db.ForeignKey(u'public_places.id'))
    user_id = db.Column(db.Integer, db.ForeignKey(u'users.user_id'))
    fav = db.Column(db.Boolean)
    updated_time = db.Column(db.DateTime)

    place = relationship(u'PublicPlace', backref = u'user_fav_places')
    user = relationship(u'User', backref = u'user_fav_places')

然后我将此模型更改为以下内容-
class UserFavPlace(db.Model):
    # This model stores the feedback from the user whether he has
    # faved a place or not
    __tablename__ = u'user_fav_places'

    public_place_id = db.Column(db.Integer, db.ForeignKey(u'public_places.id'),
            primary_key = True)
    user_id = db.Column(db.Integer, db.ForeignKey(u'users.user_id'),
            primary_key = True)
    fav = db.Column(db.Boolean)
    updated_time = db.Column(db.DateTime)

    place = relationship(u'PublicPlace', backref = u'user_fav_places')
    user = relationship(u'User', backref = u'user_fav_places')

但是,Alembic 不会生成正确的升级和降级语句。似乎没有添加新引入的主键约束。
def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('user_fav_places', 'id')
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('user_fav_places', sa.Column('id', mysql.INTEGER(display_width=11), nullable=False))
    ### end Alembic commands ###

我不确定如何添加它。

最佳答案

我发现自动生成在检测主/外键更改方面非常糟糕。没关系,通常您无论如何都想自定义它们。

我还没有创建复合主键,但看起来这应该基于文档工作:

http://alembic.zzzcomputing.com/en/latest/ops.html#alembic.operations.Operations.create_primary_key

op.create_primary_key(
        "pk_user_fav_places", "user_fav_places",
        ["public_place_id", "user_id"]
    )

然而,你可能会遇到一个不同的问题,我在这里写过:Adding primary key to existing MySQL table in alembic

这可能已在更新版本的 alembic 中得到修复,但它可能不允许您在现有表上创建主键(请参阅上面的答案以了解原因)。如果发生这种情况,您可以自己制作 SQL 并使用 op.execute 运行它。

希望有帮助!

关于sqlalchemy - Alembic 不制作复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28958969/

相关文章:

python - SQLAlchemy session 重新连接

python - sqlalchemy 数据库表被锁定

python - 在 sqlalchemy 核心中使用 IFNULL

python - 从不同子文件夹的子文件夹相对导入 python 模块

python - Flask-migrate 使 SQLite 迁移而不是 PSQL

python - Flask-SQLAlchemy 小写索引 - 跳过功能,SQLAlchemy 反射不支持

sqlite - Sqlalchemy sqlite url 相对于 home 或环境变量

SqlAlchemy:如果不存在则创建对象?

python - sqlalchemy mixin、外键和关系

python - alembic 是否关心其迁移文件的名称?