Difference between filter() and filter_by() method in flask, python and SQLAlchemy
- Get link
- X
- Other Apps
Difference between filter() and filter_by() method in flask, python and SQLAlchemy
In Flask using SQLAlchemy, you can use either filter()
or filter_by()
method to apply filters on queries to retrieve data from the database.
filter()
method is used to apply complex filters on queries. It takes SQLAlchemy expressions as arguments that describe the filters you want to apply. For example, you can use it to filter users whose name contains "John" and email contains "gmail.com" as follows:
from myapp.models import User users = User.query.filter(User.name.like('%John%'), User.email.like('%gmail.com%')).all()
In this example, User.query
returns a query object that can be further refined using the filter()
method. We pass the two filter expressions as arguments to the filter()
method, joined by an AND operator. The like()
method is used to match patterns in the values of the name
and email
columns.
On the other hand, filter_by()
method is used to apply simple filters on queries. It takes keyword arguments that describe the filters you want to apply. For example, you can use it to filter users whose name is "John" as follows:
from myapp.models import User users = User.query.filter_by(name='John').all()
In this example, User.query
returns a query object that can be further refined using the filter_by()
method. We pass the name='John'
filter expression as a keyword argument to the filter_by()
method.
Both filter()
and filter_by()
methods return a query object that can be further refined using other query methods or executed to retrieve the data.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments