2

我在 SQLAlchemy 中有这些模型。它定义了我的系统的一个简单操作,即喜欢一个帐户的帖子,因此每个帐户可以喜欢多个帖子,并且一个帖子可以被多个帐户(多对多)喜欢,每个看起来都很好执行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,
    )
4

1 回答 1

2

如何使用:

    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函数返回iso format一个日期时间,另一方面,它date.today()是一个日期对象,sqlalchemy 不知道应该如何解析,因为有各种日期格式。因此,通过明确声明日期格式,您应该得到您想要的结果。

于 2020-06-01T08:42:47.343 回答