Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy get list of ids from a query

How do I get a list of ids instead of a list of SQLAlchemy objects? Currently I'm doing this:

[x.id for x in random_query.all()]

Is there a better way of doing this, preferably by only using SQLAlchemy statements.

like image 587
JelteF Avatar asked Jul 03 '14 18:07

JelteF


People also ask

What does SQLAlchemy query return?

It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session. It creates a SQL JOIN against this Query object's criterion and apply generatively, returning the newly resulting Query. It returns exactly one result or raise an exception.

How do I get column values in SQLAlchemy?

Get value by column name The given task can be performed by first creating an engine with sqlalchemy, connecting with the database, and executing an SQL query with the connection. The SQL query will contain the name of the column/columns whose values we want and then we will get a result object.

What is all () in SQLAlchemy?

add a mapped entity to the list of result columns to be returned. 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.

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance. While not directly relevant to this section, if we want to get at it, we should use the inspect() function to access it).


2 Answers

SQLAlchemy Session has method scalars for getting list of values without mapping.

SQLAlchemy 1.4+ style:
results = Session.scalars(select(Table.id)).all()

SQLAlchemy old styles:

results = Session.scalars(Session.query(Table.id)).all()
results = Session.scalars(Table.query.with_entities(Table.id)).all()

Actual results:

[1, 2, 3, 4, 5]
like image 142
Ivan Kvas Avatar answered Sep 16 '22 14:09

Ivan Kvas


Using SQLAlchemy 1.4+, you can you use the core-style select syntax:

ids = session.execute(select(MyModel.spam).distinct()).all()
like image 22
snakecharmerb Avatar answered Sep 17 '22 14:09

snakecharmerb