杰瑞科技汇

Python SQLAlchemy as怎么用?

Of course! "Python SQLAlchemy as" can refer to a few key concepts in the SQLAlchemy library. I'll break them down from the most common to more advanced uses.

Python SQLAlchemy as怎么用?-图1
(图片来源网络,侵删)

The Most Common Use: as in a Query (for Aliasing)

This is the most frequent use of the as keyword in SQLAlchemy. It's used to create an alias for a table or a subquery. This is essential for:

  • Self-joins: Joining a table to itself (e.g., finding an employee and their manager).
  • Multiple joins to the same table: Joining the same table multiple times with different conditions.
  • Readability: Giving a long, complex subquery a short, memorable name.

How it Works:

You use the .alias() method on a table object. The resulting alias object can then be used just like the original table object in queries.

Example: Finding Employees and Their Managers

Let's model an Employee table where an employee has a manager_id that points to another employee in the same table.

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, select
from sqlalchemy.orm import sessionmaker
# Setup (using Core for this example)
engine = create_engine("sqlite:///:memory:")
metadata = MetaData()
# Define the Employee table
employees = Table(
    'employees',
    metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String),
    Column('manager_id', Integer, nullable=True) # Points to another employee's id
)
# Create the table in the database
metadata.create_all(engine)
# Insert some sample data
conn = engine.connect()
conn.execute(employees.insert(), [
    {'id': 1, 'name': 'Alice', 'manager_id': None},   # CEO
    {'id': 2, 'name': 'Bob', 'manager_id': 1},      # Reports to Alice
    {'id': 3, 'name': 'Charlie', 'manager_id': 1},  # Reports to Alice
    {'id': 4, 'name': 'David', 'manager_id': 2},    # Reports to Bob
])
conn.commit()
# --- The "as" part in action ---
# Create an alias for the employees table to use for the manager
# This is like saying "let's call the employees table 'managers' for this query"
managers = employees.alias('managers')
# Build the query to find each employee and their manager's name
stmt = select(
    employees.c.name.label('employee_name'),
    managers.c.name.label('manager_name')
).select_from(
    employees.join(
        managers,
        employees.c.manager_id == managers.c.id,
        isouter=True # Use a LEFT JOIN to include employees with no manager
    )
)
# Execute and print the results
result = conn.execute(stmt)
print("Employee and Manager Report:")
for row in result:
    print(f"{row.employee_name} reports to {row.manager_name or 'No one'}")
# Expected Output:
# Employee and Manager Report:
# Alice reports to No one
# Bob reports to Alice
# Charlie reports to Alice
# David reports to Bob

as in SQLAlchemy ORM (for Aliasing and Model Labels)

When using the ORM (Object-Relational Mapper), the concept is the same, but the syntax is slightly different.

Python SQLAlchemy as怎么用?-图2
(图片来源网络,侵删)

Example: Self-join with ORM Models

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship, declarative_base
Base = declarative_base()
class Employee(Base):
    __tablename__ = 'employees_orm'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    manager_id = Column(Integer, ForeignKey('employees_orm.id'))
    # This relationship points to the Manager (an Employee)
    manager = relationship("Employee", remote_side=[id])
    def __repr__(self):
        return f"<Employee(name='{self.name}')>"
# Setup
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# Insert data
alice = Employee(name='Alice')
bob = Employee(name='Bob', manager=alice)
charlie = Employee(name='Charlie', manager=alice)
david = Employee(name='David', manager=bob)
session.add_all([alice, bob, charlie, david])
session.commit()
# --- The "as" part in action with ORM ---
# We need to alias the Employee class itself
Manager = Employee.alias('manager')
# Query using the alias
# We select from the Employee class and join it with its alias
query = session.query(
    Employee.name,
    Manager.name
).join(
    Manager,
    Employee.manager_id == Manager.id,
    isouter=True
)
print("\nORM Employee and Manager Report:")
for row in query:
    print(f"{row.Employee_name} reports to {row.Manager_name or 'No one'}")
# Expected Output:
# ORM Employee and Manager Report:
# Alice reports to No one
# Bob reports to Alice
# Charlie reports to Alice
# David reports to Bob

Notice the difference in accessing columns in the ORM result: row.Employee_name and row.Manager_name. This is because SQLAlchemy uses the alias name you provided as a prefix.


as in Python's with Statement (Context Managers)

This is a standard Python feature, not specific to SQLAlchemy, but it's extremely common when working with database connections and sessions. The as keyword is used to assign the result of a context manager to a variable.

Example: Using sessionmaker with with

This is the highly recommended way to handle sessions in modern SQLAlchemy.

# Assuming the same ORM setup as in the previous example
# The 'as session' part assigns the session object to the 'session' variable
# The session is automatically created when entering the 'with' block
# and automatically closed (and rolled back if not committed) when exiting
with Session() as session:
    # All database operations happen inside this block
    new_employee = Employee(name='Eve', manager=bob)
    session.add(new_employee)
    session.commit()
    # You can also query
    all_employees = session.query(Employee).all()
    print("\nAll employees after adding Eve:")
    for emp in all_employees:
        print(emp)
# After the 'with' block, the session is closed.
# Trying to use it here would raise an error.
# session.query(Employee).all() # Would raise an InvalidRequestError

Summary

Context What as does Example
SQLAlchemy Core Query Creates a table alias to use in joins. managers = employees.alias('managers')
SQLAlchemy ORM Query Creates a model alias to use in joins. Manager = Employee.alias('manager')
Python with Statement Assigns the context manager's result to a variable. with Session() as session:

In short, when you see as in a SQLAlchemy query, it's almost certainly about creating an alias. When you see it with a with statement, it's about variable assignment in a context manager.

分享:
扫描分享到社交APP
上一篇
下一篇