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来进行预处理,这是一种方法

相关内容

热门资讯

举措透视!wepoker游戏安... 举措透视!wepoker游戏安装教程,wepoker有辅助插件吗,第三方教程(有挂秘笈)-哔哩哔哩>...
发现透视"wepok... 发现透视"wepoker辅助工具好用吗"开挂(透视)辅助器(9分钟了解高科技教程)发现透视"wepo...
模块透视!hhpoker可以控... 【亲,hhpoker可以控制吗 这款游戏可以开挂的,确实是有挂的,很多玩家在这款hhpoker可以控...
实测透视"微扑克发牌... 实测透视"微扑克发牌机制详解"开挂(透视)辅助器(玩家亲测黑科技教程)实测透视"微扑克发牌机制详解"...
秘籍透视!wepoker可以透... >>您好:wepoker辅助器官方确实是有挂的,很多玩家在这款wepoker辅助器官方游戏中打牌都会...
正版透视"wepok... 正版透视"wepoker透视软件下载"开挂(透视)辅助软件(科技分享揭秘教程)正版透视"wepoke...
模块透视!pokemmo辅助官... wepoker模拟器哪个好用 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四...
曝光透视"微扑克辅助... 曝光透视"微扑克辅助期是干嘛的"开挂(透视)辅助工具(记者发布总结教程)曝光透视"微扑克辅助期是干嘛...
大纲透视!约局吧辅助脚本,aa... aapoker安装包怎么使用是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用...
必看透视"微扑克辅助... 必看透视"微扑克辅助器官网入口"开挂(透视)辅助脚本(今日公布必赢教程)必看透视"微扑克辅助器官网入...