在SQLAlchemy声明性模型中自动设置属性

时间:2015-09-10 21:53:01

标签: python sqlalchemy

这是我正在尝试做的一个人为的例子。我有两个相关对象之一的子对象(这里是'home和'work')。

我想知道是否有一种明智的方法让列确定它们所属的类别(Address.type)在使用各自的关系绑定时自动设置。

也许通常有更好的方法来处理这种情况?

class Person(Base):
    __tablename__ = 'person'

    id = Column(Integer, primary_key=True)

    home_addresses = relationship('Address', primaryjoin="and_(Person.id==Address.person_id, Address.type == 'home')")
    work_addresses = relationship('Address', primaryjoin="and_(Person.id==Address.person_id, Address.type == 'work')")


class Address(Base):
    __tablename__ = 'address'

    id = Column(Integer, primary_key=True)
    person_id = Column(Integer, ForeignKey('person.id'))
    type = Column(String)


p = Person()
p.home_addresses.append(Address())  # automatically set type to 'home'
p.work_addresses.append(Address())  # automatically set type to 'work'

1 个答案:

答案 0 :(得分:1)

您可以使用orm events

from sqlalchemy import event
@event.listens_for(Person.home_addresses, 'append')
def receive_append(target, value, initiator):
    # set the address type to home
    value.type = 'home'
    return value