![]() |
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 DatabaseIn 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. Python3
![]() Parent & Child Tables Filtering a list attribute using SQLAlchemyUsing 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 Python3
Output ![]() Parents with child Ravi or Pinki Example 2: In the following Example we are retrieving data from parent table where child name start with Ra and having even id number Python3
Using exists()The exists() method helps us to check if a subquery produces any results or not. It gives us a Boolean value, either True or False depending on whether the subquery has any rows, in its result set. In the following example we are retrieving the parent details whose all children names ends with “a”. Example: In the above code, we have used the filter method to apply a filter condition to the parent selection. Inside the filter, there is a subquery created using exists(). This subquery checks if there exists at least one child associated with a parent whose name does not end with ‘a’. The subquery uses and_() to combine two conditions:
Python3
Output ![]() Parents with all children names ends with a Using JoinsWe can apply filters on list attributes using joins. Please refer SQLAlchemy Core Join for knowing more about Joins in Sqlalchemy. Example: In the following example we are retrieving the parent details where parent with child names “Venkat”,”likitha” or “manasa” Python3
Output Using LoopLOOP statement could be used to run a block of code or set of statements, again and again, depending on the condition.We can filter list attributes using loops also. Example: In the following example we first retrieve the all parent details from using query() and then we iterate over the parent data and check if parent children names parent is in required names or not. Python3
Output |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |