如何在sqlalchemy关系中使用日期(时间)算法?

2024-10-05 10:57:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有些东西看起来像这样:

from sqlalchemy import sa
from sqlalchemy.ext.declarative import declarative_base

metadata = sa.MetaData(schema='myschema')
Base = declarative_base(metadata=metadata)


class MyThing(Base):
     __tablename__ = 'thing'

     ...
     id = sa.Column('id', sa.Integer, primary_key=True)

     recent_things = sa.orm.relationship(
         'OtherThing',
         primaryjoin="and(MyThing.id==OtherThing.thing_id,"
         "OtherThing.timestamp >= now - 60)"
     )



class OtherThing(Base):
    __tablename__ = 'others'

    ...
    thing_id = sa.Column('thing_id', sa.Integer, nullable=False)
    timestamp = sa.Column('timestamp', sa.DateTime)

不幸的是,这不起作用。我还尝试了>= remote('now - 60')和其他一些变体。每一个都失败,但有各种例外。在

如何正确设置此查询以执行我想要的操作?我发现了一个建议使用ADDDATE函数的结果,但它似乎不再是sqlalchemy的一部分了。在


Tags: fromimportidbasesqlalchemysacolumntimestamp
1条回答
网友
1楼 · 发布于 2024-10-05 10:57:11

尝试使用现在功能()而不是现在:

recent_things = sa.orm.relationship(
    'OtherThing', primaryjoin="and(MyThing.id==OtherThing.thing_id,"
    "OtherThing.timestamp >= func.now() - 60)"
)

这是func的文档页:http://docs.sqlalchemy.org/en/rel_0_9/core/functions.html#sqlalchemy.sql.functions.func

相关问题 更多 >

    热门问题