sqlalchemy lookup tables

前端 未结 3 1143
忘了有多久
忘了有多久 2021-01-07 13:47

Hi I have a table in 3NF form

ftype_table = Table(
    \'FTYPE\',
    Column(\'ftypeid\', Integer, primary_key=True),
    Column(\'typename\', String(50)),
          


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 14:20

    Just create a cache of FileType objects, so that the database lookup occurs only the first time you use a given file type:

    class FileTypeCache(dict):
        def __missing__(self, key):
            obj = self[key] = Session.query(FileType).filter_by(typename=key).one()
            return obj
    
    filetype_cache = FileTypeCache()
    
    file=File()
    file.size=10
    file.filetype= filetype_cache['PPT']
    

    should work, modulo typos.

提交回复
热议问题