I've got database table with columns year_id, month_id and day_id (all are NUMBER). I want to make a query which filters dates. In order to simplify it I want to add hybrid_property to join the mentioned fields together into date.
class MyModel(Base): __table__ = Base.metadata.tables['some_table'] @hybrid_property def created_on(self): return date(self.year_id, self.month_id, self.day_id)
But when I make query
session.query(MyModel).filter(MyModel.created_on==date(2010, 2, 2))
I get an error TypeError: an integer is required (got type InstrumentedAttribute)
.
Is there another way of doing such filter: I can't modify db schema (so the fields should remain the same), but at the same time it's difficult to compare dates against 3 separate columns?
You need to add an expression to your hybrid attribute, but it might be different depending on your RDBMS. See below for an example of one for sqlite
:
@hybrid_property
def created_on(self):
return date(self.year_id, self.month_id, self.day_id)
@created_on.expression
def created_on(cls):
# @todo: create RDBMS-specific fucntion
# return func.date(cls.year_id, cls.month_id, cls.day_id)
# below works on Sqlite: format to YYYY-MM-DD
return (func.cast(cls.year_id, String) + '-' +
func.substr('0' + func.cast(cls.month_id, String), -2) + '-' +
func.substr('0' + func.cast(cls.day_id, String), -2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.