python - SQLAlchemy 忽略查询中的特定字段

标签 python postgresql sqlalchemy flask-sqlalchemy

我正在使用带有 Flask 的 SQLAlchemy 与 postgres 数据库对话。我有一个 Customer 模型,它有一个像这样定义的 date_of_birth 字段

class Customer(Base):
    __tablename__ = 'customer'
    id = Column(Integer, primary_key=True)
    date_of_birth = Column(Date)

现在,我正尝试按这样的最低年龄过滤这些内容:

q.filter(date.today().year - extract('year', Customer.date_of_birth) - cast((today.month, today.day) < (extract('month', Customer.date_of_birth), extract('day', Customer.date_of_birth)), Integer) >= 5)

但生成的 SQL 似乎忽略了 day 部分并将其替换为常量。看起来像这样

SELECT customer.date_of_birth AS customer_date_of_birth,
FROM customer
WHERE (2017 - EXTRACT(year FROM customer.date_of_birth)) - CAST(EXTRACT(month FROM customer.date_of_birth) > 2 AS INTEGER) >= 5

当我从查询中删除 day 部分时,生成的 SQL 完全相同。为什么 sqlalchemy 会忽略它?

最佳答案

这是因为您要比较两个 元组:

(today.month, today.day) < (extract('month', Customer.date_of_birth), extract('day', Customer.date_of_birth))

元组比较的方式是,比较第一个元素,如果不相等则返回结果,否则返回第二个元素的比较结果。因此,在您的情况下,这与将第一个元素放在一起是相同的。

您应该比较的不是两个元组,而是tuple_。构造,像这样:

(today.month, today.day) < tuple_(extract('month', Customer.date_of_birth), extract('day', Customer.date_of_birth))

关于python - SQLAlchemy 忽略查询中的特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42301842/

相关文章:

python - PySpark 在 Synapse 链接服务之间切换

python - 加入多个 re.compile 时插入负前瞻

java - 为什么我的数据库连接在尝试执行 JOOQ 生成的 SQL 时关闭?

postgresql - 为什么 Postgres 拒绝在某些设置中使用复合索引?

python - SQLAlchemy中关系和外键模块的使用

sqlalchemy - Airflow 1.10 - 调度程序启动失败

python - 在 SQLAlchemy 生成的以下查询中,最可能导致 "ORA-00936: missing expression"的原因是什么?

python - 未绑定(bind)本地错误 : local variable 'arith_flex' referenced before assignment

python - 使用 ConfigParser 读取没有节名的文件

sql - 减少查询数量,可能是通过表模式?