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.
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.
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.
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.
_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).
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]
Using SQLAlchemy 1.4+, you can you use the core-style select syntax:
ids = session.execute(select(MyModel.spam).distinct()).all()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With