我有以下课程:
class Request(BaseMixin, Base):
id = Column(Integer, primary_key=True)
scan_title = Column(String)
status = Column(String)
ip = Column(String)
option_title = Column(String)
priority = Column(Integer)
owner = Column(String)
# servers = relationship('Request2Server', back_populates='request')
servers = association_proxy('request_servers','server')
class Server(BaseMixin, Base):
ip = Column(String, primary_key=True, autoincrement=False)
servercmdb_id_fk = Column(Integer, ForeignKey('servercmdb.id'))
servercmdb = relationship('ServerCMDB', backref=backref('servercmdb', uselist=False))
last_report = Column(String)
status = association_proxy('server_requests', 'statusk')
class Request2Server(AssocBaseMixin, Base):
request_id_fk = Column(Integer, ForeignKey('request.id'), primary_key=True)
server_ip_fk = Column(String, ForeignKey('server.ip'), primary_key=True)
status = Column(String)
data = Column(String)
error = Column(String)
request_rel = relationship('Request', backref='request_servers')
server = relationship('Server', backref='server_requests') #, backref='requests')
def __init__(self, server=None):
self.server = server
和代码:
from db_alchemy.tables import Request, Server, Request2Server
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
e = create_engine("sqlite:///datafiles/data.sqlite")
Base.metadata.create_all(e)
Session = sessionmaker(bind=e)
session = Session()
Debugger connected.
r = Request(scan_title='R1')
s1 = Server(ip='IP1')
s2 = Server(ip='IP2')
s3 = Server(ip='IP2')
session.add_all([r,s1,s2,s3])
r.servers.append(s1)
r.servers.append(s2)
r.servers.append(s3)
r.servers
[<db_alchemy.tables.Server object at 0x7f3cc0527e80>, <db_alchemy.tables.Server object at 0x7f3cc0451630>, <db_alchemy.tables.Server object at 0x7f3cc05e87b8>]
我想知道是否可以替换列表:
[<db_alchemy.tables.Server object at 0x7f3cc0527e80>, <db_alchemy.tables.Server object at 0x7f3cc0451630>, <db_alchemy.tables.Server object at 0x7f3cc05e87b8>]
带有一些类似查询的对象,通过它我可以轻松访问过滤的数据。我知道有可能在经典关系中配置过lazy ='dynamic',但是association_proxy会将其转为列表。
关联代理值:
r.servers
[<db_alchemy.tables.Server object at 0x7fd841a09278>, <db_alchemy.tables.Server object at 0x7fd841a09438>]
关系值
r.request_servers
<sqlalchemy.orm.dynamic.AppenderQuery object at 0x7fd841970080>
我想通过类似查询的对象来给association_proxy值,例如:
r.servers
<sqlalchemy.orm.dynamic.AppenderQuery object at 0x7fd841970080>