With Peewee I'm trying to use limit as follows:
one_ticket = Ticket.select().limit(1)
print one_ticket.count()
This prints out 5 however. Does anybody know what's wrong here?
With Peewee I'm trying to use limit as follows:
one_ticket = Ticket.select().limit(1)
print one_ticket.count()
This prints out 5 however. Does anybody know what's wrong here?
Try running peewee
in debug mode, which is actually just setting up the python logging
module to handle logging.DEBUG
level items:
import logging
logging.basicConfig(
format='[%(asctime)-15s] [%(name)s] %(levelname)s]: %(message)s',
level=logging.DEBUG
)
# From here, you can now perform your query, and you should see peewee's debug output using the logging module.
one_ticket = Ticket.select().limit(1)
print one_ticket.count()
Ideally, you should see the raw query.
[2013-11-19 10:41:33,555] [peewee] DEBUG]: ('SELECT Count(t1."id") FROM "ticket" AS t1 LIMIT 1', [])
. This still leaves me clueless as to why the count is 5 though. Any ideas? –
Ironmonger one_ticket.wrapped_count()
instead. The more direct one_ticket.count()
will default to counting the number of items from primary key, as seen in the source: github.com/coleifer/peewee/blob/master/peewee.py#L1653 –
Testicle This is a very old issue - this was fixed years ago. The count()
method now takes into account any limit or ordering applied.
In [1]: from peewee import *
In [2]: db = SqliteDatabase(':memory:')
In [3]: class Ticket(db.Model):
...: pass
...:
In [4]: Ticket.create_table()
In [5]: for i in range(10):
...: Ticket.create()
...:
In [6]: Ticket.select().limit(1).count()
Out[6]: 1
In [7]: Ticket.select().count()
Out[7]: 10
This prints out 5 however. Does anybody know what's wrong here?
To get the number of results of a LIMIT query you can pass the iterator over len()
, like len(one_ticket)
.
What is wrong is that .limit(1)
and .count()
issue two different SQL queries, and COUNT
usually costs a lot more than a query with LIMIT 1
over the database.
For example, this is useful if you want to know if there exists some or more than one result in a query. Django's ORM QuerySet method .exists()
queries for a full row with LIMIT 2
instead of a COUNT
because COUNT
hits the DB harder than LIMIT 2
© 2022 - 2024 — McMap. All rights reserved.