Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy ORM - restricting columns at query time (select) - column_property

I know I can lazy load columns from a table:

session.query(MyTable).options(defer(colname) 
      for colname in ['col4', 'col5', ..,  'colN'])

I only want the first 3 columns, so can shorten that to the following:

session.query(MyTable).options(defer(col.name) 
      for col.name in MyTable.__table__.columns
      if col.name not in ['col1', 'col2', 'col3'])

Because MyTable has a few extra column_propertys which aren't listed in MyTable.__table__.columns, these get included in the query even though I don't want them.

So is there a construct to express what I want directly as a restriction? e.g. something like

session.query(MyTable).options(XXselect('col1', 'col2', 'col3'))
like image 532
EoghanM Avatar asked Mar 15 '26 13:03

EoghanM


1 Answers

If you only want the values, you can just call :

session.query(Mytable.col1, MyTable.col2, MyTable.col3).

If you want the full object with deferred columns, MyTable.__table__.columns should give you all the columns regardless of the mixins.

like image 68
madjar Avatar answered Mar 17 '26 01:03

madjar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!