Python 当孩子们准备好了,怎么做?

Python 当孩子们准备好了,怎么做?,python,sqlalchemy,Python,Sqlalchemy,考虑以下一对多模型 class Person(Base): id things = relationship('Thing') def some_magic_here(): pass class Thing(Base): id person_id = ForeignKey(person.id) 我想要实现的是,当我做以下事情时: p = Person() thing1 = Thing() thing2 = Thing() p.thing

考虑以下一对多模型

class Person(Base):
    id
    things = relationship('Thing')

    def some_magic_here():
        pass
class Thing(Base):
    id
    person_id = ForeignKey(person.id)
我想要实现的是,当我做以下事情时:

p = Person()
thing1 = Thing()
thing2 = Thing()
p.things = [thing1, thing2]

方法
some\u magic\u here
将在将内容1和内容2添加为子项之前执行一些处理工作您需要事件系统:

e、 g.类似于:

@listens_for(Person.things, 'append')
def some_magic_here(target, value, initiator):
    # do whatever

难道不是
p.things=[thing1,thing2]
只是覆盖
Person
things
属性吗?@aIKid有没有办法覆盖这个默认行为?嗯。。你到底想要什么?我觉得你有点搞糊涂了。阅读sqlalchemy文档,这里有一个关于如何制作一对多的教程relationship@aIKid最初,p.things=[东西(id=1,新桌子)]。然后当我设置p.things=[Thing(id=2,new desk)]时,会调用一些魔术,检查Thing(id=2)并返回,告知已经有一个类似的desk当你设置
p.things=anythings
时,前面的值将被覆盖!