Subquery from pypika documentation not working

146 Views Asked by At
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')
)

I have picked the code directly from the documentation of pypika https://pypika.readthedocs.io/en/latest/2_tutorial.html#joining-tables-and-subqueries

yet it gives me the following error:

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

Did I do something wrong? Is this just broken? I already tried simplifying the code or using PostgreSQLQuery, but same result.

1

There are 1 best solutions below

0
user2741831 On
from pypika import Query, Table, Order, Field, Tables, JoinType, functions as fn
from pypika import functions as fn
from datetime import date

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')
)

print(q)

its as_ not _as. They need to fix their documentation