首页 > 解决方案 > Flask + SQLAlchemy:为表创建索引列

问题描述

我在使用 SQLALchemy 为 sqlite3 数据库中的表创建索引时遇到困难。每次通过 celery 的周期性任务向数据库中添加一行时,都会对该行进行索引。

也许我的理解有缺陷。我认为db.Index('scheduleId', Schedule.taskId)一旦第一行数据到达数据库,就会自动创建一个值为 1 的新“scheduleId”列?

应用程序/模型.py

class Schedule(db.Model):
    __tablename__ = 'schedule'
    taskId = db.Column(db.String(50), primary_key=True)

    def __init__(self, **kwargs):
        super(Schedule, self).__init__(**kwargs)

db.Index('scheduleId', Schedule.taskId)

应用程序/任务/test.py

@periodic_task(run_every=crontab(minute="*"), bind=True)
def periodic_run_get_manifest(self):
    with app.app_context():
        task_id = self.request.id
        s = Schedule()
        s.taskId = task_id
        db.session.add(s)
        db.session.commit()
        rowId = db.session.query(Schedule).order_by(Schedule.scheduleId.desc()).first()

当定期任务运行时,我收到以下错误:

AttributeError:类型对象“Schedule”没有属性“scheduleId”

标签: pythonflasksqlalchemyflask-sqlalchemy

解决方案


修改你的类模型

class Schedule(db.Model):
        __tablename__ = 'schedule'
        taskId = db.Column(db.String(50), unique=True)
        scheduleId = db.Column(db.Integer, primary_key=True) # will create index and autoincrement both

自动增量文档

索引文件


推荐阅读