我正在使用带有 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/