Skip to content
Advertisement

How to create ASC/DESC indexes using sqlalchemy?

I have the following table declaration

from gino import Gino

db = Gino()

class DatasetUpdateModel(db.Model):
    __tablename__ = "dataset_updates"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    dataset_id = db.Column(db.Integer, nullable=False)
    created_at = db.Column(db.DateTime(timezone=True))

    __table_args__ = (
        db.Index(
            "dataset_updates_dataset_id_created_at_idx",
            "dataset_id",
            "created_at",
        ),
    )

I need to create the following index:

CREATE INDEX ON dataset_updates(dataset_id, created_at DESC);

How can I specify DESC order?

Advertisement

Answer

Instead of referring to the columns as strings, refer to them as their actual (object) references and add the .desc() modifier as required:

    __table_args__ = (
        db.Index(
            "dataset_updates_dataset_id_created_at_idx",
            dataset_id,
            created_at.desc(),
        ),
    )
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement