SQLAlchemy Filter in List
SQLAlchemy is a Python's powerful Object-Relational Mapper that, provides flexibility to work with Relational Databases. SQLAlchemy provides a rich set of functions that can be used in SQL expressions to perform various operations and calculations on the data using Python. In SQLAlchemy, we can filter on a list attribute using any, exists, joins, and loops.
Prerequisites:
Table Creation in Database
In this section, we are making a connection with the database, we are creating the structure of two tables with parent-child relationships. Also, we are inserting data in both tables.
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
name = Column(String(length=30))
children = relationship('Child')
class Child(Base):
__tablename__ = 'children'
id = Column(Integer, primary_key=True)
name = Column(String(length=30))
parent_id = Column(Integer, ForeignKey('parent.id'))
parent = relationship('Parent')
#create engine for MySql DB
engine = create_engine('mysql+pymysql://user_name:password@host:port/db_name')
Base.metadata.create_all(engine)
# Create a session
Session = sessionmaker(bind=engine)
session = Session()
#Create Parent objects and child objects
parent1 = Parent(name='Ramesh', children=[Child(name='Pinki'), Child(name='Venkat')])
parent2 = Parent(name='Sharadha', children=[Child(name='Rama'),Child(name='Nikitha')])
parent3=Parent(name='Parent3',children=[Child(name='Ravi'),Child(name='Likitha'),Child(name="Manasa")])
#adding data to DB
session.add_all([parent1,parent2,parent3])
#commiting chagnges
session.commit()

Filtering a list attribute using SQLAlchemy
Using any()
The any() method in SQLAlchemy is used to check if any element in a collection or list of elements matches a certain condition or not. It is used as part of a query expression to filter records based on conditions.
Syntax: list_object.any(conditions)
Example: In the following example we are retrieving the data of parents having the child Ravi or Pinki
# query to fecth parand details having child Child1 or Child6
query = session.query(Parent).filter(
Parent.children.any(Child.name.in_(["Ravi", "Pinki"])))
# fetching the data from DB
result = query().all()
# printing the data
for data in query:
print(data.id, data.name)
for child in data.children:
print(child.id, child.name)
print()