SQLAlchemy - 通过父模型访问子模型的列(一对一关系)

时间:2017-06-25 10:54:40

标签: python sqlalchemy

我有两种模式,它们之间有一对一的关系。我想访问ItemDataItem的列(例如item = Item(); item.value)。我试图覆盖__getattr__,但这种方法被SQLAlachemy基础模型强烈使用。任何帮助赞赏。

class Item(Model):
    __tablename__ = "item_data"
    id = Column(Integer, primary_key=True)

    data = relationship("ItemData", back_populates="_item", uselist=False,
                        foreign_keys="ItemData._item_id")

class ItemData(Model):
    __tablename__ = "items_data"
    id = Column(Integer, primary_key=True)

    _item_id = Column(Integer, ForeignKey("items.id"))
    _item = relationship("Item", back_populates="data",
                            foreign_keys=[_item_id])

    value = Column(Integer)

1 个答案:

答案 0 :(得分:0)

我通过编写应该应用于Item的类装饰器解决了这个问题。

from sqlalchemy.ext.hybrid import hybrid_property

def direct_data_getter(cls):
    '''Provide direct access to attributes of data.'''
    fields = set(cls.data_cls.__mapper__.columns.keys()) - set(dir(cls))
    for field in fields:
        method = hybrid_property(
            lambda self, field=field: getattr(self.data, field)
        )
        setattr(cls, field, method)
    return cls