views:

404

answers:

3

Hello everyone!

Could anyone explain the difference between filter and filter_by functions in SQLAlchemy? I am confused and can't really see the difference. Which one should I be using?

Thanks, Boda Cydo

+3  A: 

filter_by is used for simple queries on the column names like

db.users.filter_by(name='Joe')

The same can be accomplished with filter by writing

db.users.filter(db.users.name=='Joe')

but you can also write more powerful queries containing expressions like

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

Daniel Velkov
great! now i know the difference! thank you!
bodacydo
+2  A: 

filter_by uses keyword arguments, whereas filter allows pythonic filtering arguments like filter(User.name="john")

jellybean
thanks for the answer!
bodacydo
Hmm. Wouldn't the latter one be filter(User.name=="john") ?
Matthew Schinckel
@Matthew: Correct. Thanks.
jellybean
A: 

We actually had these merged together originally, i.e. there was a "filter"-like method that accepted *args and **kwargs, where you could pass a SQL expression or keyword arguments (or both). I actually find that a lot more convenient, but people were always confused by it, since they're usually still getting over the difference between column == expression and keyword = expression. So we split them up.

zzzeek