我的模型有两列Date
和Time
列。我希望我的查询将这些列一起返回并格式化。我尝试使用这样的hybrid_property
:
@hybrid_property
def mydate_and_mytime(self):
return self.mydate.strftime("%Y-%m-%d") + " + " self.mytime.strftime("%H:%M")
但是,在该属性中,self.mydate
和self.mytime
的类型为InstrumentedAttribute
,其中没有strftime
方法,并且会引发错误。
如何进行以下查询?
session.query(MyModel.mydate, MyModel.mytime, MyModel.mydate_and_mytime)
答案 0 :(得分:4)
除了简单表达式之外,混合属性需要getter和expression部分。利用内置函数组合日期和时间,然后格式化。
from datetime import datetime
from sqlalchemy.ext.hybrid import hybrid_property
@hybrid_property
def mydate_and_mytime(self):
combine = datetime.combine(self.mydate, self.mytime)
return combine.strftime('%Y-%m-%d %H:%M')
@mydate_and_mytime.expression
def mydate_and_mytime(cls):
# return a sqlalchemy expression based on the columns
# uses MySQL timestamp and date_format functions
combine = db.func.timestamp(cls.mydate, cls.mytime)
return db.func.date_format(combine, '%Y-%m-%d %H:%i')
在我看来,格式化应留在属性之外,以便比较实际的日期时间,但这是你的电话。