Let's say I have a basic table like so:
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(30))
How can I pass a variable in to my Select statement so I can decide what to order by at runtime?
That is, I can have a call like this:
db.session.scalars(select(OrgModel).order_by(OrgModel.id.desc()).all()
but I can't have
order_field = 'name'
db.session.scalars(select(OrgModel).order_by(order_field).all()
How do you accomplish this?
Let's say I have a basic table like so:
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(30))
How can I pass a variable in to my Select statement so I can decide what to order by at runtime?
That is, I can have a call like this:
db.session.scalars(select(OrgModel).order_by(OrgModel.id.desc()).all()
but I can't have
order_field = 'name'
db.session.scalars(select(OrgModel).order_by(order_field).all()
How do you accomplish this?
Share Improve this question asked Feb 16 at 2:55 froopydoopfroopydoop 1158 bronze badges1 Answer
Reset to default 1Found out that order_by can take a string, although the documentation for that is in a weird place not right by the other docs for order_by. If you import asc and desc from sqlalchemy, you can call
order_by(desc("id")) and it will work