【问题标题】:SQLAlchemy mapping table columns with filters带有过滤器的 SQLAlchemy 映射表列
【发布时间】:2017-01-17 10:05:44
【问题描述】:

我在 PostgreSQL 中有一个表,其中包含有关文档的信息。让我们这么说吧:

table: doc

id (int)
name (string)
type (int)

type 是文档的类别(例如 1 - 护照,2 - 保险等)。此外,我还有不同的表格,其中包含每种文档类型的附加信息。

table: info

id (int)
doc_id (fk)
info (additional columns)

我希望有一个 SQLAlchemy 模型来处理与其附加信息相关联的每种类型的文档,并且能够管理要显示的列(对于 Flask-Admin,如果它很重要的话)。

现在要将两个表连接到某种“模型”中,我使用了类似 SQLAlchemy 文档中的Mapping Table Columns(当只有一种类型的文档时):

class DocMapping(db.Model):

    __table__ = doc.__table__.join(info)
    __mapper_args__ = {
        'primary_key': [doc.__table__.c.id]
    }

现在的问题是:如何根据 doc.type 列创建多个继承自 db.Model 的类(DocPassportMapping、DocInsuranceMapping 等)?

类似的东西:

__table__ = doc.__table__.join(info).filter(doc.type)

这显然行不通,因为我们这里没有 query 对象。

【问题讨论】:

    标签: python postgresql flask sqlalchemy flask-admin


    【解决方案1】:

    如果我对您的理解正确,您希望拥有一个基于DocMappinginheritance hierarchy,并以DocMapping.type 作为多态标识。由于您没有提供完整的示例,因此这里有一个有点相似的结构。它肯定有差异,但应该适用于您的。这在连接映射的顶部使用single table inheritance

    模型:

    In [2]: class Doc(Base):
       ...:     id = Column(Integer, primary_key=True, autoincrement=True)
       ...:     name = Column(Unicode)
       ...:     type = Column(Integer, nullable=False)
       ...:     __tablename__ = 'doc'
       ...:     
    
    In [3]: class Info(Base):
       ...:     __tablename__ = 'info'
       ...:     doc_id = Column(Integer, ForeignKey('doc.id'), primary_key=True)
       ...:     value = Column(Unicode)
       ...:     doc = relationship('Doc', backref=backref('info', uselist=False))
       ...:     
    
    In [4]: class DocMapping(Base):
       ...:     __table__ = Doc.__table__.join(Info)
       ...:     __mapper_args__ = {
       ...:         'primary_key': (Doc.id, ),
       ...:         # These declare this mapping polymorphic
       ...:         'polymorphic_on': Doc.type,
       ...:         'polymorphic_identity': 0,
       ...:     }
       ...:     
    
    In [5]: class Passport(DocMapping):
       ...:     __mapper_args__ = {
       ...:         'polymorphic_identity': 1,
       ...:     }
       ...:     
    
    In [6]: class Insurance(DocMapping):
       ...:     __mapper_args__ = {
       ...:         'polymorphic_identity': 2,
       ...:     }
       ...:     
    

    测试:

    In [7]: session.add(Insurance(name='Huono vakuutus',
       ...:                       value='0-vakuutus, mitään ei kata'))
    
    In [8]: session.commit()
    
    In [15]: session.query(DocMapping).all()
    Out[15]: [<__main__.Insurance at 0x7fdc0a086400>]
    
    In [16]: _[0].name, _[0].value
    Out[16]: ('Huono vakuutus', '0-vakuutus, mitään ei kata')
    

    问题是:您可能不希望从db.Model 继承的多个类作为基类,而是从DocMapping 继承的类。作为层次结构,它更有意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2017-01-23
      • 2019-08-20
      • 1970-01-01
      • 2020-02-13
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多