python - Understanding intermediary SQL statements in SQLAlchemy -
so have table, , want have users able view table in whichever order they'd like. here's example:
class thing(base): __tablename__ = 'thing' id = column(integer, primary_key=true) amount = column(integer) date = column(datetime, default=datetime.now()) def __init__(self, amount): self.amount = amount
so i'd make following query:
if sort == 'amount': orderby = thing.amount.desc() elif sort == 'date': orderby = thing.date.desc() things = dbsession.query(thing).order_by(orderby).all()
main questions:
- when set orderby statement, calling or statement being set?
- am doing correctly , efficiently?
can filters?
filterby = thing.amount == 5
things = dbsession.query(thing).filter_by(filterby).all()
thanks!
ans 1: when giving syntax return can check type of syntax like
when write
in [5]: thing.amount.desc() out[5]: <sqlalchemy.sql.expression._unaryexpression object @ 0x199a5d0>
it create 1 object of type expression._unaryexpression. expression can give sqlalchemy when want unary operation. when print in [6]: = thing.amount.desc()
in [7]: print thing.amount desc
so when query run converted in thing.amount desc
. when create expression not call thing, create structure of query.
ans: 2 when creating query create object needed. filter , order need expression if pass directly order_by
or filter
create object same internally. can use both way.
ans: 3
in [8]: thing.amount == 5 out[8]: <sqlalchemy.sql.expression._binaryexpression object @ 0x1a1dbd0>
this expression can give expression filter_by.
you more idea expression sqlalchemy site.
Comments
Post a Comment