我在 SQLAlchemy 中有这些模型。它定义了我的系统的一个简单操作,即通过一个帐户喜欢一个帖子,因此每个帐户可以喜欢多个帖子,并且一个帖子也可以被许多帐户喜欢(多对多),每个看起来都很好 execpt Likes_per_day
列属性,我希望它显示帐户每天的点赞数。当我运行此代码并保持其运行时,看起来 date.today()
将在运行时执行,并且始终显示 rundate 的点赞数,而不是今天。
因此,我计划使用列属性获取每天的点赞数。正确的方法是什么?
class Account(Base):
__tablename__ = 'account'
id = Column(
Integer,
primary_key=True
)
likes_per_day = column_property(
select([func.count(Like.id)])
.where(Like.account_id == id)
.where(func.date(Like.created_at) == date.today()) # Problem is here
.correlate_except(Like)
)
class Like(Base):
__tablename__ = 'like'
id = Column(
Integer,
primary_key=True
)
post_id = Column(
Integer,
ForeignKey('post.id')
)
account_id = Column(
Integer,
ForeignKey('account.id')
)
created_at = Column(
DateTime,
nullable=False,
default=datetime.utcnow,
)
最佳答案
如何使用:
likes_per_day = column_property(
select([func.count(Like.id)])
.where(Like.account_id == id)
.where(func.date(Like.created_at) == bindparam(
'today',
callable_=lambda:date.today().isoformat()
)
)
.correlate_except(Like),
deferred=True
)
date
函数返回 DateTime 的 iso 格式
,另一方面,date.today()
是日期对象由于各种日期格式,sqlalchemy 不知道应该如何解析。
因此,通过明确声明日期格式,您应该得到您想要的结果。
关于python - 在 SQLAlchemy 列属性中使用 python 日期函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62127464/