4

有以下几种: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 数据库不允许创建这样的索引。但是如果把name字段去掉表的名字,创建索引就没有问题了:

CREATE INDEX order_fio_desc ON student USING btree (fio DESC)

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

4

1 回答 1

1

postgresql_ops您可以像在其他索引中一样使用关键字参数指定排序。这将使以下内容有效:

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);
于 2019-07-09T14:06:18.597 回答