Tôi có một tập hợp các bảng trông giống như:SQLAlchemy: bảng Relation với hỗn tiểu học trọng điểm
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),
)
lớp ORM của tôi trông giống như:
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"
)
Vì vậy, trong hệ thống của tôi, mỗi hành động là duy nhất được xác định bởi sự kết hợp của id luồng công việc và tên của nó. Tôi muốn mỗi hành động có thuộc tính parents
và children
đề cập đến hành động của cha mẹ và con của nó. Mỗi hành động có thể có nhiều phụ huynh và trẻ em.
Vấn đề xảy ra khi tôi có một chức năng như:
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.append(parent)
session.commit()
tôi nhận được một lỗi như:
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')
Làm thế nào để tôi có được mối quan hệ để thiết lập workflow_id chính xác?
Tại sao bạn cần phải có 'workflow_id' trong bảng' action_dependencies'? – van
Bởi vì khóa chính cho một hành động là một kết hợp của tên và workflow_id của nó. Nếu workflow_id không có trong action_dependencies, sẽ không có cách nào để cho biết các hành động của luồng công việc mà phụ thuộc đang đề cập đến. –
Điểm tốt, điểm tốt. Hãy để tôi suy nghĩ ... – van