python - 在 SQLAlchemy 列属性中使用 python 日期函数

标签 python python-3.x date sqlalchemy

我在 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/

相关文章:

python - 执行 Python 脚本而不生成带有子进程的新进程

python - 如何将 Postgres 日期时间字段设置为 Odoo 日期时间字段

python - 无法创建 Django 模型的实例

python-3.x - python没有定义递归函数吗?

python - Pandas:应用函数:TypeError:不支持的操作数类型 -: 'unicode' 和 'unicode'

PyCharm 中的 Python3 语法

java - 无法将字符串转换为正确的日期格式

Python:将字符串中的多个日期格式更改为日期时间格式

java - simpledateformat 解析未正确解析日期