Get list of query results in Peewee - python

Considering to switch from SQLAlchemy to peewee but have a fundamental question as I'm not able to find an example of this. I want to execute a query that returns a list of the matched objects. What works is get which returns a single record:
Topping.select().where(Topping.id==jalapenos.id).get()
What I want to get is a list of results for which all examples indicate that I should iterate. Is there a way to get a list of results from:
Topping.select(Topping).where(Topping.stock > 0)

A peewee query is lazily executed. It returns an iterator which must be accessed before the query will execute, either by iterating over the records or calling the execute method directly.
To force the query to execute immediately:
results = Topping.select().execute()
To convert query results to a list:
query = Topping.select().where(Topping.stock > 0)
toppings = list(query)
# OR
toppings = [t for t in query]
Note that you can greatly simplify your query for retrieving a single entity with:
Topping.get(Topping.id==jalapenos.id)

Related

MySQL Cursor object assigned outside if condition can't be used inside the said if block [duplicate]

Why do I get nothing when I execute cursor.fetchall() twice after a cursor.execute()? Is there anyway of preventing this from happening? Do I need to store the information on a variable? Is it suppose to work this way?
fetchall does what it says--it fetches all. There's nothing left after that. To get more results, you'd need to run another query (or the same query again).
From the python db-api 2.0 specification:
cursor.fetchall()
Fetch all (remaining) rows of a query result, returning
them as a sequence of sequences (e.g. a list of tuples).
Note that the cursor's arraysize attribute can affect the
performance of this operation.
cursor.fetchone()
Fetch the next row of a query result set, returning a
single sequence, or None when no more data is
available. [6]

How to use SQLalchemy in_ with a list object?

I was trying to query a database based on some pre selected items and ran into a weird situation. I started with pre selecting some parameters that I would like use as filter in a query from one of the tables in the database:
MX_noaa_numbers = list(Events_df[Events_df['flareclass'].str.contains('M|X')].noaanumber.unique())
Which produces a list such as:
[11583,11611,11771,11777,11778,11865,12253,11967,11968,...,12673]
But when I tried to obtain the results using:
session.query(ActiveRegion).filter(sql.or_(ActiveRegion.noaa_number1.in_(MX_noaa_numbers),
ActiveRegion.noaa_number2.in_(MX_noaa_numbers),
ActiveRegion.noaa_number3.in_(MX_noaa_numbers))).all()
it returns me an empty list. However if I print MX_noaa_numbers and copy the output inside the in_() statement substituting the object name (MX_noaa_numbers) I actually get the results as I should. Am I missing something or I actually ran into some weird error?
Thanks!

The result of the sqlalchemy query return tuple but I want to as a list

I used below code:
session.query(Content).order_by(desc(Content.date)).limit(25).offset(0)
I get result, it filter my repeat data, but I hope save this repeat data.
I know the sqlalchemy query result as tuple.
How to do or code not use tuple return query result ?
As stated in the docs:
all()
Return the results represented by this Query as a list.
This results in an execution of the underlying query.
So this should work:
session.query(Content).order_by(desc(Content.date)).limit(25).offset(0).all()

PYMONGO - How do I use the query $in operator with MongoIDs?

So I am trying to use the $in operator in Pymongo where I want to search with a bunch of MongoIDs.
First I have this query to find an array of MongoIDs:
findUsers = db.users.find_one({'_id':user_id},{'_id':0, 'f':1})
If I print the findUsers['f'] it looks like this:
[ObjectId('53b2dc0b24c4310292e6def5'), ObjectId('53b6dbb654a7820416a12767')]
These object IDs are user ids and what I want to do is to find all users that are in the users collection with this array of ObjectID. So my thought was this:
foundUsers = db.users.find({'_id':{'$in':findUsers['f']}})
However when I print the foundUsers the outcome is this:
<pymongo.cursor.Cursor object at 0x10d972c50>
which is not what I normally get when I print a query out :(
What am I doing wrong here?
Many thanks.
Also just for you reference, I have queried in the mongo shell and it works as expected:
db.users.find({_id: {$in:[ObjectId('53b2dc0b24c4310292e6def5'), ObjectId('53b6dbb654a7820416a12767')]}})
You are encountering the difference between findOne() and find() in MongoDB. findOne returns a single document. find() returns a mongoDB cursor. Normally you have to iterate over the cursor to show the results. The reason your code works in the mongo shell is that the mongo shell treats cursors differently if they return 20 documents or less - it handles iterating over the cursor for you:
Cursors
In the mongo shell, the primary method for the read operation is the
db.collection.find() method. This method queries a collection and
returns a cursor to the returning documents.
To access the documents, you need to iterate the cursor. However, in
the mongo shell, if the returned cursor is not assigned to a variable
using the var keyword, then the cursor is automatically iterated up to
20 times [1] to print up to the first 20 documents in the results.
http://docs.mongodb.org/manual/core/cursors/
The pymongo manual page on iterating over cursors would probably be a good place to start:
http://api.mongodb.org/python/current/api/pymongo/cursor.html
but here's a piece of code that should illustrate the basics for you. After your call to find() run this:
for doc in findUsers:
print(doc)

Django limit query

I am trying to run a Django query that will limit the returned results to 5 items. This is easy, except for the fact that the query will not always return 5 items. In that case, a statement like this (my code) fails:
users = User.objects.filter(username__istartswith = name)[5].only('Person__profile_picture', 'username')
If the query only returns a single result, I get an index out of range error. Is there a way to instruct Django to give me a maximum of 5 results without crashing on me? Is the standard solution to just wrap everything up in a try block? Or do I need to write a raw SQL query to accomplish this?
As in doc: https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets
For example, this returns the first 5 objects (LIMIT 5):
Entry.objects.all()[:5]
users=User.objects.filter(username__istartswith=name)
[:5].values(‘Person__profile_picture’,’username’)

Categories