sqlalchemy lookup tables

前端 未结 3 1141
忘了有多久
忘了有多久 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:38

    Since declarative_base and zzzeek code does not work with sqlalchemy 0.4, I used the following cache so that new objects also stay unique if they are not present in the db

    class FileTypeCache(dict):
        def __missing__(self, key):
            try:
              obj = self[key] = Session.query(FileType).filter_by(typename=key).one()
              return obj
            except InvalidRequestError:
              return obj=self[key]= FileType(key)
              return obj
    

    override eq of FileType

    class FileType(object):
        def __init__(self, typename)
           self.typename=typename
        def __eq__(self):
            if isinstance(other, FileType):
                return self.typename == other.typename
            else:
                return False
    

提交回复
热议问题