回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有一套桌子,看起来像:</p>
<pre><code>workflows = Table('workflows', Base.metadata,
Column('id', Integer, primary_key=True),
)
actions = Table('actions', Base.metadata,
Column('name', String, primary_key=True),
Column('workflow_id', Integer, ForeignKey(workflows.c.id), primary_key=True),
)
action_dependencies = Table('action_dependencies', Base.metadata,
Column('workflow_id', Integer, ForeignKey(workflows.c.id), primary_key=True),
Column('parent_action', String, ForeignKey(actions.c.name), primary_key=True),
Column('child_action', String, ForeignKey(actions.c.name), primary_key=True),
)
</code></pre>
<p>我的ORM课程看起来像:</p>
<pre><code>class Workflow(Base):
__table__ = workflows
actions = relationship("Action", order_by="Action.name", backref="workflow")
class Action(Base):
__table__ = actions
children = relationship("Action",
secondary=action_dependencies,
primaryjoin=actions.c.name == action_dependencies.c.parent_action,
secondaryjoin=actions.c.name == action_dependencies.c.child_action,
backref="parents"
)
</code></pre>
<p>所以在我的系统中,每个操作都是由工作流id和它的名称的组合唯一标识的。我希望每个操作都有引用其父操作和子操作的<code>parents</code>和<code>children</code>属性。每个动作可以有多个父对象和子对象。</p>
<p>当我有如下功能时,就会出现问题:</p>
<pre><code>def set_parents(session, workflow_id, action_name, parents):
action = session.query(db.Action).filter(db.Action.workflow_id == workflow.id).filter(db.Action.name == action_name).one()
for parent_name in parents:
parent = session.query(db.Action).filter(db.Action.workflow_id == workflow.id).filter(db.Action.name == parent_name).one()
action.parents.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(parent)
session.commit()
</code></pre>
<p>我得到一个错误,比如:</p>
<pre><code>IntegrityError: (IntegrityError) action_dependencies.workflow_id may not be NULL u'INSERT INTO action_dependencies (parent_action, child_action) VALUES (?, ?)' (u'directory_creator', u'packing')
</code></pre>
<p>如何获得正确设置工作流id的关系?</p>