You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pypika文档中子查询代码报错:'Field'对象不可调用

Pypika子查询示例报错:TypeError: 'Field' object is not callable

问题描述

我直接照搬Pypika官方文档中的子查询示例代码:

from pypika import Query, Table, Field, Tables, Order

history, customers = Tables('history', 'customers')
last_purchase_at = Query.from_(history).select(
    history.purchase_at
).where(history.customer_id==customers.customer_id).orderby(
    history.purchase_at, order=Order.desc
).limit(1)
q = Query.from_(customers).select(
    customers.id, last_purchase_at._as('last_purchase_at')
)

运行后抛出错误:

Traceback (most recent call last):
  File "/home/user/trash/pikatest/main.py", line 10, in <module>
    customers.id, last_purchase_at._as('last_purchase_at')
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Field' object is not callable

试过简化代码、改用PostgreSQLQuery,问题依然存在。想问是我的操作有误,还是文档示例本身有问题?

解决方案

这是Pypika文档示例的错误,问题出在_as('last_purchase_at')的调用方式上:在Pypika中,_as是一个只读属性而非可调用方法,不能通过括号传参。

你可以通过以下两种方式修正代码:

方式一:使用as_()方法(推荐)

from pypika import Query, Table, Field, Tables, Order

history, customers = Tables('history', 'customers')
last_purchase_at = Query.from_(history).select(
    history.purchase_at
).where(history.customer_id==customers.customer_id).orderby(
    history.purchase_at, order=Order.desc
).limit(1)
q = Query.from_(customers).select(
    customers.id, last_purchase_at.as_('last_purchase_at')
)

方式二:使用Alias类显式声明别名

from pypika import Query, Table, Field, Tables, Order, Alias

history, customers = Tables('history', 'customers')
last_purchase_at = Query.from_(history).select(
    history.purchase_at
).where(history.customer_id==customers.customer_id).orderby(
    history.purchase_at, order=Order.desc
).limit(1)
q = Query.from_(customers).select(
    customers.id, Alias(last_purchase_at, 'last_purchase_at')
)

修正后的代码可以正常生成目标SQL,不会再触发TypeError。

内容的提问来源于stack exchange,提问作者user2741831

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:42:53