AssociationProxywitheagerloadingandAsyncSession
创始人
2024-09-20 19:30:11
0

使用Python的SQLAlchemy库,可以使用异步会话(AsyncSession)从数据库中使用AssociationProxy来进行查询,同时使用预处理方式(eager loading)来提高查询效率。

下面是一个示例代码:

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import declarative_base, relationship, Session
from sqlalchemy.ext.associationproxy import association_proxy

Base = declarative_base()


class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    addresses = relationship("Address", back_populates="user")

    all_addresses = association_proxy('addresses', 'email')


class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    email = Column(String)
    user_id = Column(Integer, ForeignKey('users.id'))

    user = relationship("User", back_populates="addresses")

engine = create_async_engine('postgresql+asyncpg://user:password@localhost/mydatabase')

async with engine.begin() as conn:
    await conn.run_sync(Base.metadata.drop_all)
    await conn.run_sync(Base.metadata.create_all)

async with AsyncSession(engine) as session:
    async with session.begin():
        # create objects
        user1 = User(name='user1', addresses=[Address(email='address1')])
        user2 = User(name='user2', addresses=[Address(email='address2'), Address(email='address3')])
        user3 = User(name='user3', addresses=[Address(email='address4')])
        session.add_all([user1, user2, user3])

    async with session.begin():
        # query objects using AssociationProxy and eager loading
        users = await session.execute(
            select(User).options(joinedload(User.addresses)).order_by(User.id)
        )
        for user in users.scalars():
            print(user.name, user.all_addresses)

    session: Session = session
    await session.commit()

在这个示例中,我们首先定义了两个模型类User和Address,并使用了association_proxy方法来生成all_addresses属性,指向User对象下的Address表中的email属性。然后我们使用AsyncSession和create_async_engine方法创建了一个异步会话和数据库引擎,并且连接到了一个名为'mydatabase'的postgres数据库。

接着,我们在数据库中生成了模型类对应的表,并且向其中插入了一些示例数据。最后,我们查询了所有用户的所有地址,并将得到的结果输出到控制台中。

这里我们使用了options方法中的joinedload来进行预处理,这是一种方法

相关内容

热门资讯

记者揭秘!智星菠萝辅助(透视辅... 记者揭秘!智星菠萝辅助(透视辅助)拱趴大菠萝辅助神器,扑克教程(有挂细节);模式供您选择,了解更新找...
一分钟揭秘!约局吧能能开挂(透... 一分钟揭秘!约局吧能能开挂(透视辅助)hhpoker辅助靠谱,2024新版教程(有挂教学);约局吧能...
透视辅助!wepoker模拟器... 透视辅助!wepoker模拟器哪个好用(脚本)hhpoker辅助挂是真的,科技教程(有挂技巧);囊括...
透视代打!hhpkoer辅助器... 透视代打!hhpkoer辅助器视频(辅助挂)pokemmo脚本辅助,2024新版教程(有挂教程);风...
透视了解!约局吧德州真的有透视... 透视了解!约局吧德州真的有透视挂(透视脚本)德州局HHpoker透视脚本,必胜教程(有挂分析);亲,...
六分钟了解!wepoker挂底... 六分钟了解!wepoker挂底牌(透视)德普之星开辅助,详细教程(有挂解密);德普之星开辅助是一种具...
9分钟了解!wpk私人辅助(透... 9分钟了解!wpk私人辅助(透视)hhpoker德州透视,插件教程(有挂教学);风靡全球的特色经典游...
推荐一款!wepoker究竟有... 推荐一款!wepoker究竟有透视(脚本)哈糖大菠萝开挂,介绍教程(有挂技术);囊括全国各种wepo...
每日必备!wepoker有人用... 每日必备!wepoker有人用过(脚本)wpk有那种辅助,线上教程(有挂规律);wepoker有人用...
玩家必备教程!wejoker私... 玩家必备教程!wejoker私人辅助软件(脚本)哈糖大菠萝可以开挂,可靠技巧(有挂神器)申哈糖大菠萝...