sqlalchemy backref 性能差

1 投票
1 回答
1128 浏览
提问于 2025-04-15 19:04

你好,我有以下这些表:

nfiletable = Table(
    'NFILE', base.metadata,
    Column('fileid', Integer, primary_key=True),
    Column('path', String(300)),
    Column('filename', String(50)),
    Column('filesize', Integer),
    schema='NATIVEFILES')#,autoload=True,autoload_with=engine)

sheetnames_table=Table(
    'SHEETNAMES', base.metadata, schema='NATIVEFILES', 
    autoload=True, autoload_with=engine)


nfile_sheet_table=Table(
    'NFILE_SHEETNAME',base.metadata,
    Column('fileid', Integer, ForeignKey(nfiletable.c.fileid)), 
    Column('sheetid', Integer, ForeignKey(sheetnames_table.c.sheet_id)),
    schema='NATIVEFILES')

还有对应的映射器:

nfile_mapper=mapper(Nfile,nfiletable)

mapper(Sheet, sheetnames_table, properties={
    'files': relation(
        Nfile, secondary=nfile_sheet_table,
        primaryjoin=(sheetnames_table.c.sheet_id==nfile_sheet_table.c.sheetid),
        secondaryjoin=(nfile_sheet_table.c.fileid==nfiletable.c.fileid),
        foreign_keys=[nfile_sheet_table.c.sheetid,nfile_sheet_table.c.fileid],
        backref='sheets')
})

当我执行以下操作时:

upl = Session.query(Nfile).filter_by(fileid=k).one()
sheetdb=[]
for sheet in sheetstoadd:
     s = sheetcache[sheetname]
     sheetdb.append(s)
upl.sheets = sheetdb
Session.save(upl)
Session.flush()

这行代码 upl.sheets = sheetdb 要花很长时间。看起来每个表的所有文件都从数据库中加载了。有什么办法可以防止这种情况发生吗?

1 个回答

1

如果NFile.sheets引用了一个很大的集合,可以在反向引用上加上“lazy='dynamic'”:

mapper(Sheet, sheetnames_table, properties={
    'files': relation(
        Nfile, secondary=nfile_sheet_table,
        backref=backref('sheets', lazy='dynamic'))
})

所有的primaryjoin/secondaryjoin/foreign_keys这些东西也不需要,因为你的nfile_sheet_table上已经有ForeignKey的设置了。

撰写回答