【问题标题】:Alembic does not make composite primary keyAlembic 不生成复合主键
【发布时间】:2015-05-11 14:39:10
【问题描述】:

我有一个 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 ###

我不确定如何添加它。

【问题讨论】:

    标签: sqlalchemy alembic


    【解决方案1】:

    我发现自动生成在检测主键/外键更改方面非常糟糕。没关系,通常你还是想自定义那些。

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

    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 运行它。

    希望有帮助!

    【讨论】:

    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2014-06-17
    • 2011-12-17
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多