如何在flask-sqlalchemy

时间:2015-12-09 21:53:33

标签: python postgresql flask flask-sqlalchemy flask-migrate

有以下内容:Flask,Flask-sqlalchemy,Flask-migrate

有一个描述该表的类:

class Student(db.Model):
    __tablename__ = 'student'

    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.Unicode(250), nullable=False, index=True)
    last_name = db.Column(db.Unicode(250), nullable=False, index=True)
    surname = db.Column(db.Unicode(250), nullable=False, index=True)
    group = db.Column(db.Unicode(250), nullable=False, index=True)
    fio = db.Column(db.Unicode(250*3))

    add_info = db.relationship('AddInfo', uselist=False, backref='student', cascade="all, delete-orphan")

    __table_args__ = (
        db.Index('fio_like', 'fio', postgresql_ops={'fio': 'text_pattern_ops'}),
        db.Index('first_name_like', 'first_name', postgresql_ops={'first_name': 'text_pattern_ops'}),
        db.Index('last_like', 'last_name', postgresql_ops={'last': 'text_pattern_ops'}),
        db.Index('surname_like', 'surname', postgresql_ops={'surname': 'text_pattern_ops'}),
        db.Index('order_fio_desc', fio.desc(), postgresql_using='btree'),
    )

    @classmethod
    def create(cls, first_name, last_name, surname, address, date_of_birth, group):
        obj = cls()

        obj.first_name = first_name
        obj.last_name = last_name
        obj.surname = surname
        obj.group = group
        obj.fio = ' '.join([last_name, first_name, surname]).strip()

        if not obj.add_info:
            obj.add_info = AddInfo()

        obj.add_info.address = address
        obj.add_info.date_of_birth = date_of_birth

        return obj

    @property
    def serialize(self):
        return {
            'id': self.id,
            'fio': self.fio,
            'group': self.group
        }

使用此查询迁移此模型以创建索引order_fio_desc时:

CREATE INDEX order_fio_desc ON student USING btree (student.fio DESC)

由于存在字段名称的名称,PostgreSQL数据库不允许创建这样的索引。但是如果要删除表名的名称字段,则创建的索引没有问题:

CREATE INDEX order_fio_desc ON student USING btree (fio DESC)

如何创建生成索引的请求?

1 个答案:

答案 0 :(得分:0)

您可以像其他索引一样使用postgresql_ops关键字arg来指定顺序。这将使以下内容有效:

db.Index(
    'order_fio_desc',
    'fio',
    postgresql_using='btree',
    postgresql_ops={'fio': 'DESC'},
),

这会在迁移文件中提供以下输出:

op.create_index('order_fio_desc', 'student', ['fio'], unique=False, postgresql_using='btree', postgresql_ops={'fio': 'DESC'})

反过来会导致所需的SQL:

CREATE INDEX order_fio_desc ON student USING btree (fio DESC);