python - 如何在 SQLAlchemy 中实现空合并运算符?

标签 python sqlalchemy null-coalescing-operator

或者我该如何使它发挥作用?

我有一个间隔对象:

class Interval(Base):
    __tablename__ = 'intervals'
    id = Column(Integer, primary_key=True)
    start = Column(DateTime)
    end = Column(DateTime, nullable=True)
    task_id = Column(Integer, ForeignKey('tasks.id'))

@hybrid_property #used to just be @property
def hours_spent(self):
    end = self.end or datetime.datetime.now()
    return (end-start).total_seconds()/60/60

还有一个任务:

class Task(Base):
    __tablename__ = 'tasks'
    id = Column(Integer, primary_key=True)
    title = Column(String)
    intervals = relationship("Interval", backref="task")

@hybrid_property  # Also used to be just @property
def hours_spent(self):
    return sum(i.hours_spent for i in self.intervals)

当然,添加所有典型的设置代码。

现在当我尝试做 session.query(Task).filter(Task.hours_spent > 3).all()

我得到 NotImplementedError: <built-in function getitem>来自 sum(i.hours_spent...行。

所以我在看this part的文档和理论上可能有某种方式我可以写一些东西来做我想做的事。 This part看起来它也可能有用,我会在此处等待答案的同时查看它;)

最佳答案

有关 SQLAlchemy 合并函数的简单示例,这可能会有所帮助:Handling null values in a SQLAlchemy query - equivalent of isnull, nullif or coalesce .

以下是该帖子中的几行关键代码:

from sqlalchemy.sql.functions import coalesce
my_config = session.query(Config).order_by(coalesce(Config.last_processed_at, datetime.date.min)).first()

关于python - 如何在 SQLAlchemy 中实现空合并运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18102109/

相关文章:

Python multiprocessing.Pool map() "TypeError: string indices must be integers, not str"

python - SQL表中的值发生变化时如何执行Python函数?

python - sqlalchemy 中关于另一个应用程序创建的新行的通知

php - 最后一个操作数为空的空合并运算符

c# - C# 中的空合并运算符 (??) 是线程安全的吗?

python - 同时读取 2 个文件中的每 4 行

python - 如何在Python中用两个数组绘制堆叠直方图

由列表索引的python数据框

python - SQLAlchemy 删除不会级联

f# - F# 中的空合并运算符?