Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all rows with keys provided in a list using SQLalchemy?

I have sequence of IDs I want to retrieve. It's simple:

session.query(Record).filter(Record.id.in_(seq)).all() 

Is there a better way to do it?

like image 204
Cheery Avatar asked Jan 14 '09 20:01

Cheery


People also ask

What does all () return SQLAlchemy?

As the documentation says, all() returns the result of the query as a list.

What is all () in SQLAlchemy?

method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.

How do I select data in SQLAlchemy?

To select data from a table via SQLAlchemy, you need to build a representation of that table within SQLAlchemy. If Jupyter Notebook's response speed is any indication, that representation isn't filled in (with data from your existing database) until the query is executed. You need Table to build a table.


1 Answers

Your code is absolutety fine.

IN is like a bunch of X=Y joined with OR and is pretty fast in contemporary databases.

However, if your list of IDs is long, you could make the query a bit more efficient by passing a sub-query returning the list of IDs.

like image 145
Adam Dziendziel Avatar answered Sep 26 '22 08:09

Adam Dziendziel