How to query database by id using SqlAlchemy?

PythonSqlModelSqlalchemy

Python Problem Overview


I need to query a SQLAlchemy database by its id something similar to

User.query.filter_by(username='peter')

but for id. How do I do this? [Searching over Google and SO didn't help]

Python Solutions


Solution 1 - Python

Query has a get function that supports querying by the primary key of the table, which I assume that id is.

For example, to query for an object with ID of 23:

User.query.get(23)

Note: As a few other commenters and answers have mentioned, this is not simply shorthand for "Perform a query filtering on the primary key". Depending on the state of the SQLAlchemy session, running this code may query the database and return a new instance, or it may return an instance of an object queried earlier in your code without actually querying the database. If you have not already done so, consider reading the documentation on the SQLAlchemy Session to understand the ramifications.

Solution 2 - Python

You can query an User with id = 1 like this

session.query(User).get(1)

Solution 3 - Python

get() is not as your expected sometimes. If your transaction was done:

>>> session.query(User).get(1)
[SQL]: BEGIN (implicit)
[SQL]: SELECT user.id AS user_id, user.name AS user_name, user.fullname AS user_fullname
FROM user
WHERE user.id = ?
[SQL]: (1,)
<User(u'ed', u'Ed Jones')>

If you are in a transaction, get() will give you the result object in memory without query the database:

>>> session.query(User).get(1)
<User(u'ed', u'Ed Jones')>

better to use this:

>>> session.query(User.name).filter(User.id == 1).first()
[SQL]: SELECT user.name AS user_name
FROM user
WHERE user.id = ?
 LIMIT ? OFFSET ?
[SQL]: (1, 1, 0)
(u'Edwardo',)

Solution 4 - Python

If you use tables reflection you might have problems with the solutions given. (The previous solutions here didn't work for me).

What I ended up using was:

session.query(object.__class__).get(id)

(object was retrieved by reflection from the database, this is why you need to use .__class__)

I hope this helps.

Solution 5 - Python

First, you should set id as the primary key.
Then you could use the query.get() method to query objects by id which is already the primary key.

Since the query.get() method to query objects by the primary key.
Inferred from Flask-SQLAlchemy documentation

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy()
db.init_app(app)

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)

def test():
    id = 1
    user = User.query.get(id)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser507220View Question on Stackoverflow
Solution 1 - PythonMark HildrethView Answer on Stackoverflow
Solution 2 - Pythonpeggygao1988View Answer on Stackoverflow
Solution 3 - Pythonpanda912View Answer on Stackoverflow
Solution 4 - PythonoctaedroView Answer on Stackoverflow
Solution 5 - PythonJustin LeeView Answer on Stackoverflow