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
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
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'))
filter_by
uses keyword arguments, whereas filter
allows pythonic filtering arguments like filter(User.name="john")
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.