使用flask-sqlalchemy构建mysql的联合索引

model如下:

class UserPost(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer)
    post_id = db.Column(db.Integer)
    insert_time = db.Column(db.DateTime)

    __table_args__ = (
        db.UniqueConstraint('user_id', 'post_id', name='uix_user_post_user_id_post_id'),
        db.Index('ix_user_post_user_id_insert_time', 'user_id', 'insert_time'),
    )

生成的sql如下:

2016-05-31 19:33:35,625 INFO sqlalchemy.engine.base.Engine
CREATE TABLE user_post (
        id INTEGER NOT NULL AUTO_INCREMENT,
        user_id INTEGER,
        post_id INTEGER,
        insert_time DATETIME,
        PRIMARY KEY (id),
        CONSTRAINT uix_user_post_user_id_post_id UNIQUE (user_id, post_id)
)


2016-05-31 19:33:35,625 INFO sqlalchemy.engine.base.Engine {}
2016-05-31 19:33:35,689 INFO sqlalchemy.engine.base.Engine COMMIT
2016-05-31 19:33:35,692 INFO sqlalchemy.engine.base.Engine CREATE INDEX ix_user_post_user_id_insert_time ON user_post (user_id, insert_time)
2016-05-31 19:33:35,692 INFO sqlalchemy.engine.base.Engine {}
2016-05-31 19:33:35,840 INFO sqlalchemy.engine.base.Engine COMMIT

推荐阅读更多精彩内容