Muriel
Muriel

Reputation: 591

Why is there a NameError from SQLAlchemy when filtering?

I'm trying to do the following in Flask-SQLAlchemy:

SELECT recipe_id
FROM UserRecipe
WHERE
  user_id == 3
 AND
  status != 'donotshow'

This is the best I've come up with so far:

user = User.query.filter_by(url=url).first_or_404()
userrecipes = UserRecipe.query.filter(user_id==user.id, status!='donotshow').with_entities(UserRecipe.recipe_id)

I get an error:

NameError: name 'user_id' is not defined

Would really appreciate some help :)

Upvotes: 0

Views: 96

Answers (1)

Christopher Peisert
Christopher Peisert

Reputation: 24134

With filter(*criterion) you need to qualify the column attributes with the class name:

userrecipes = UserRecipe.query.filter(UserRecipe.user_id==user.id, 
    UserRecipe.status!='donotshow').with_entities(UserRecipe.recipe_id)

By contrast, filter_by(**kwargs) accepts unqualified column attributes as keyword arguments:

userrecipes = UserRecipe.query.filter_by(user_id==user.id, 
    status!='donotshow').with_entities(UserRecipe.recipe_id)

Upvotes: 1

Related Questions