[英]SQLAlchemy Adjacency List - Constrain parent_id not equal to ID
I'm implementing an Adjacency List in SQL Alchemy which I have working.我在 SQL Alchemy 中实施邻接列表,我正在工作。 It's the basic example here of Node.
这是 Node.js 的基本示例。 I have it working.
我有它的工作。
class Node(Base):
__tablename__ = 'node'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('node.id'))
data = Column(String(50))
children = relationship("Node")
But, I want to enforce a constraint where the parent_id != id
.但是,我想强制执行
parent_id != id
的约束。 That is, a row can not be its own parent.也就是说,一行不能是它自己的父级。 I am not sure how to enforce this.
我不确定如何执行此操作。 Do I need to use a
@validates
or is there a DB constraint I can set up on the column(s).我需要使用
@validates
还是可以在列上设置数据库约束。
You could use either @validates
or a db constraint.您可以使用
@validates
或 db 约束。 The constraint would look like this:约束看起来像这样:
import sqlalchemy as sa
class Node(Base):
__tablename__ = 'node'
id = sa.Column(sa.Integer, primary_key=True)
parent_id = sa.Column(sa.Integer, sa.ForeignKey('node.id'))
data = sa.Column(sa.String(50))
children = orm.relationship("Node")
__table_args__ = (sa.CheckConstraint('parent_id != id'),)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.