Get all results from a Select Query without specifying columns
See original GitHub issueHi, so far I’ve read majority of the documentation on peewee. While there are plenty of instructions on how to create a SelectQuery [1][2]. There is no example on extracting everything about the results (list of rows). One would expect a query statement from SQL return a table-like. I’ve come from using SQLalchemy expression language to peewee ORM. I have no background on Flask
Throughout reading the whole documentation and a whole page of google results I’ve never found the proper use of SelectQuery.
Goal: Extract a range of entries from SQL
Not very useful as it only returns PK
db = SqliteDatabase(...)
query = User.select().where(User.id.between(0,100))
cursor = db.execute(query)
print(cursor.fetchone()) # prints primary key
If the previous one only return PK why does this return everything
query = User.select()
cursor = db.execute_sql()(*query)
print(cursor.fetchone()) # prints a row as a tuple!!
Bad practice, but works perfectly 👍
query = User.select().where(User.id.between(0,100))
rows = [row._data for row in query]
Now I’m just being hopeful
import pandas as pd
query = User.select().where(User.id.between(0,100))
pd.read_sql(query.sql()) # this is obviously incorrect
Either I am very ignorant about how ORM work… actually SQLAchemy supports this:
…or there is some missing about peewee that the developers decided it is not within the scope of peewee to take care of. So is there a method from query that is on the lines of
query = User.select().where(User.id.between(0,100))
rows = query.all() # a list of results or rows, no need to be dictionary but preferable
Similar concerns:
Issue Analytics
- State:
- Created 6 years ago
- Comments:6 (4 by maintainers)
Top GitHub Comments
I’m not sure about your definition for the
User
model you’ve used in your examples, but presumably it has fields on it besides the ID?Let’s look at some examples:
The user model in these examples has a username field, as well as an implicit “id” field. As you will see,
User.select()
will select all the columns in the table by default. The query is iterable and the results it yields are, by default, instances of the model class. You can, if you like, get different objects from the cursor as the examples below show:There’s no magic “.all()” you need… simply iterate over the
Select
query itself. If you explicitly want a cursor-wrapper (though there’s no need, as the query itself is fine to use), you can use the return value ofSelect.execute()
.Does this answer your question?
PS - I’m finding it hard to believe you’ve read the docs if you are confused on this… it’s covered by the quick-start if you’d like a refresher.
Calling
execute()
on a select query returns a cursor-like object but it is not a db-api cursor. Again, not necessary as the query itself should be treated like a cursor.