Alembic不会使复合主键

Sid*_*rth 3 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')
Run Code Online (Sandbox Code Playgroud)

然后,我将此模型更改为以下模型-

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')
Run Code Online (Sandbox Code Playgroud)

但是,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 ###
Run Code Online (Sandbox Code Playgroud)

我不确定如何添加它。

Rac*_*ers 5

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

我还没有创建复合主键,但是它似乎可以基于文档工作:

http://alembic.zzzcomputing.com/zh_CN/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"]
    )
Run Code Online (Sandbox Code Playgroud)

但是,您可能会遇到一个不同的问题,我在这里写下:在Alembic中向现有MySQL表添加主键

此问题可能已在Alembic的最新版本中得到修复,但可能无法让您在现有表上创建主键(有关原因,请参见上面的答案)。如果发生这种情况,您可以自己编写SQL并使用op.execute运行它。

希望有帮助!