Fix Python – Difference between filter and filter_by in SQLAlchemy

Question

Asked By – bodacydo

Could anyone explain the difference between filter and filter_by functions in SQLAlchemy?
Which one should I be using?

Now we will see solution for issue: Difference between filter and filter_by in SQLAlchemy


Answer

filter_by is used for simple queries on the column names using regular kwargs, like

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

The same can be accomplished with filter, not using kwargs, but instead using the ‘==’ equality operator, which has been overloaded on the db.users.name object:

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

You can also write more powerful queries using filter, such as expressions like:

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

This question is answered By – Daniel

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0