Closed TerehinAV closed 8 months ago
We would need to strip out the order by
in order for that to work. I'd suggest instead of using .exists()
to check .count()
(Peewee will wrap the inner query so this problem is avoided). Alternatively, you can clean up your code and simplify the exists part -- I'm not sure that even calling .exists()
is sensible here?
# Strip out the order by
query = (User
.select(
User.id, User.telegram_id, User.first_name, User.last_name, User.username,
pw.fn.MAX(Receipt.receipt_date).alias('last_date'),
pw.fn.COUNT(pw.fn.DISTINCT(pw.fn.DATE(Receipt.receipt_date))).alias(
'days_with_receipts'))
.join(Receipt, on=(User.id == Receipt.user_id))
.where(Receipt.receipt_date >= pw.fn.NOW() - pw.SQL("INTERVAL '30 DAY'"))
.group_by(User.id, User.telegram_id, User.first_name, User.last_name, User.username)
.order_by(pw.SQL('days_with_receipts').desc(), pw.SQL('last_date').desc()))
if query.order_by().exists():
# ...
# OR - use .count()
query = (User
.select(
User.id, User.telegram_id, User.first_name, User.last_name, User.username,
pw.fn.MAX(Receipt.receipt_date).alias('last_date'),
pw.fn.COUNT(pw.fn.DISTINCT(pw.fn.DATE(Receipt.receipt_date))).alias(
'days_with_receipts'))
.join(Receipt, on=(User.id == Receipt.user_id))
.where(Receipt.receipt_date >= pw.fn.NOW() - pw.SQL("INTERVAL '30 DAY'"))
.group_by(User.id, User.telegram_id, User.first_name, User.last_name, User.username)
.order_by(pw.SQL('days_with_receipts').desc(), pw.SQL('last_date').desc()))
if query.count():
...
# OR simplify
query = (User
.select()
.join(Receipt, on=(User.id == Receipt.user_id))
.where(Receipt.receipt_date >= pw.fn.NOW() - pw.SQL("INTERVAL '30 DAY'")))
if query.exists():
... do the full query here now.
Origin SQL query
Peewee code
Peewee generated query
If I call query.exists(), than it raises an exception with text:
This is because exists() generates such query to test record's existance:
And it is true, in this case there is no such field.
Please give me a hint how to avoid or fix it.
python version 3.9 peewee version 3.14.8