In this bankruptcy, we are able to speak how to practice filter out and additionally positive filter operations in conjunction with their codes.
Resultset represented through Query object may be subjected to sure criteria with the aid of the use of filter() method. The preferred utilization of clear out method is as follows −
session.query(class).filter(criteria)
In the subsequent example, resultset obtained via SELECT question on Customers desk is filtered by a situation, (ID>2) −
result = session.query(Customers).filter(Customers.id>2)
This announcement will translate into following SQL expression −
SELECT customers.id
AS customers_id, customers.name
AS customers_name, customers.address
AS customers_address, customers.email
AS customers_email
FROM customers
WHERE customers.id > ?
Since the certain parameter (?) is given as 2, most effective those rows with ID column>2 could be displayed. The entire code is given underneath −
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
engine = create_engine('sqlite:///sales.db', echo = True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Customers(Base):
__tablename__ = 'customers'
id = Column(Integer, primary_key = True)
name = Column(String)
address = Column(String)
email = Column(String)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
session = Session()
result = session.query(Customers).filter(Customers.id>2)
for row in result:
print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
The output displayed in the Python console is as follows −
ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com
ID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com