我正在尝试使用属性“ year”来计算对象实例的年龄。
class User(db.Model):
__tablename__ = 'user'
__table_args__ = {'schema': 'data'}
id = db.Column(db.Integer, primary_key=True, server_default=db.FetchedValue())
birthday = db.Column(db.Date)
@hybrid_method
def age(self):
return datetime.datetime.now().year - self.birthday.year
而
test = User.query.first()
test.year
返回20(正确),以下查询返回错误
test = User.query.filter(User.age==20).all()
AttributeError:既不是'InstrumentedAttribute'对象,也不是 与User.birthday关联的“比较器”对象具有一个属性 '年'
如何获取解析的属性?
根据评论进行编辑: 解决方案1:
@hybrid_property
def age(self):
return datetime.datetime.today().year - self.birthday.year
@age.expression
def age(cls):
return datetime.datetime.today().year - func.year(cls.birthday)
基于SQLAlchemy - Querying with DateTime columns to filter by month/day/year的解决方案2:
@hybrid_property
def age(self):
return datetime.datetime.today().year - self.birthday.year
@age.expression
def age(cls):
return datetime.datetime.today().year - extract('year', cls.birthday)