python - SQLAlchemy,如何将混合表达式设置为 'understand' 日期时间?

标签 python sqlite sqlalchemy

我正在尝试为 Person 的声明映射类设置一个 SQLAlchemy 混合属性,该类有一个名为 birth_dateDateTime 字段表示此人的出生日期。

我想设置一个代表人的年龄的@hybrid_property,如下所示:

class Person(Base):
    __tablename__ = 'person'
    name: str = Column(String)
    date_of_birth: DateTime = Column(DateTime)

    #works fine after the objects are loaded
    @hybrid_property
    def age(self):
        today = date.today()
        if self.date_of_birth:
            return today.year - self.date_of_birth.year - (
                    (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
    
    @age.expression
    def age(cls):   #Don't know how to set this up
        pass

我在为混合属性设置 expression 时遇到问题。据我所知,该表达式应该返回一个 SQL 语句,这将有助于过滤/查询数据库中的老人年龄。

为此,以下 SQL 有效

SELECT (strftime('%Y', 'now') - strftime('%Y', person.date_of_birth)) - (strftime('%m-%d', 'now') < strftime('%m-%d', person.date_of_birth)) as age from person

但我不知道如何“告诉”表达式使用此 SQL(或者即使它是解决此问题的正确方法。)我尝试使用 text像这样:

@age.expression
def age(cls):
    current_time = datetime.utcnow()   
    return text(f"{current_time.year} - strftime('%Y', '{cls.date_of_birth}')")

但是没有用。我不知道如何告诉表达式将 SQL 语句用作虚拟列的选择。 (那将是年龄列)

目标是能够过滤和查询 age 属性,如下所示:

session.query(Person).filter(Person.age > 25)

请提供帮助。

最佳答案

混合属性的这一部分需要返回一个可执行的 SQLAlchemy 子句。由于 Postgres 已经有一个合适的函数,你可以直接使用它:

import sqlalchemy as sa

@age.expression
def age(cls):
    return sa.func.age(cls.date_of_birth)

函数:docs , 寻找 age(timestamp)

或在MySQL :

@age.expression
def age(cls):
    return sa.func.timestampdiff('year', cls.date_of_birth, sa.func.curdate())

或者在 SQLite 中:

@age.expression
def age(cls):
  strftime = sa.func.strftime

  year_diff = strftime('%Y', 'now') - strftime('%Y', cls.date_of_birth)
  # If the month and date of the current year are before the
  # month and date of birth, then we need to subtract one year
  # because the "birthday" hasn't happened yet.
  is_partial_year = strftime('%m-%d', 'now') < strftime('%m-%d', cls.date_of_birth)

  return year_diff - is_partial_year

关于python - SQLAlchemy,如何将混合表达式设置为 'understand' 日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70305321/

相关文章:

python - Tornado URL 查询参数

python - 使用 QSqlTableModel 和 QTableView 模型和 View 布局,是否可以在我的表中有一列来隐藏行

python - 用 uuid 替换整数 id 字段

python - 如何在 DataFrame 的每一行上添加两列的 value_counts?

python - x = None 或 object() 是否等于显式检查?

每 30 秒或特定时间间隔后的 Python Tkinter 调用事件

android - SQLite 数据库 : Create multiple tables dynamically at runtime?

sqlite - 使用 SQLite3 创建数据库和表

python - 过滤 Flask Marshmallow 中的嵌套字段

python - SQLAlchemy (w/Postgres) - 如何将全文搜索限制为多个索引的一列?