Implementing alias in SQLAlchemy
SQL alias is a method of giving a temporary name for a table that is more convenient and readable. SQL alias facilitates a simple name to be used in place of a complex table name when it has to be used multiple times in a query. The alias() function in sqlalchemy.sql module represents an SQL alias. Let us now see how to implement alias in practice.
from sqlalchemy.sql import alias tablename.alias("a")
Get the books table from the Metadata object initialized while connecting to the database. use the alias table name while executing the query and get all the results using fetchall() function. Use a for loop to iterate through the results.
The below query selects the records where book_id > 3 with “b” as an alias name for the BOOKS table.
Python3
# Get the `books` table from the Metadata object from sqlalchemy.sql import alias, select BOOKS = meta.tables[ 'books' ] b = BOOKS.alias( "a" ) s = select([b]).where(b.c.book_id > 2 ) # Fetch all the records result = engine.execute(s).fetchall() # View the records for record in result: print ( "\n" , record) |
Output:
SQLAlchemy Core – Using Aliases
In this article, we are going to see Aliases in SQLAlchemy Core using Python.