[FIXED] Flask error or 404 query resulting in SQL error


I’m trying to clean up some of my Flask code. I have the following line that works:

user = User.query.filter_by(username=username).first()

But my preference is to use this so it can throw a 404. However the above code works but gives an error:

user = User.query.get_or_404(username=username)

TypeError: get_or_404() got an unexpected keyword argument ‘username’. If I try this:

user = User.query.get_or_404(username)

An error is also displayed:

[SQL: SELECT “user”.id AS user_id, “user”.username AS user_username,
“user”.email AS user_email, “user”.password_hash AS
user_password_hash, “user”.about_me AS user_about_me, “user”.last_seen
as user_last_seen, “user”.is_confirmed AS user_is_confirmed,
“user”.confirmed_on AS user_confirmed_on FROM “user” WHERE “user”.id =
%(pk_1)s] [Parameters: {‘pk_1’: ‘john’}]

How do I use this query? The error seems to be trying to enter a name as an id which apparently expects a number.


In flask-sqlalchemy, like get(pk), get_or_404(param) also expects the primary key of the model inside the parameter. In your case, your username is not the primary key of the User model.

Instead, you can use user = User.query.filter_by(username=username).first_or_404() to get 404 if user not exists.

Answered By – MD Obaidullah Al-Faruk

Answer Checked By – Katrina (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published