Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy邻接列表-约束父\u id不等于id_Python_Database_Sqlalchemy_Constraints - Fatal编程技术网

Python SQLAlchemy邻接列表-约束父\u id不等于id

Python SQLAlchemy邻接列表-约束父\u id不等于id,python,database,sqlalchemy,constraints,Python,Database,Sqlalchemy,Constraints,我正在SQL Alchemy中实现一个邻接列表,我正在使用它。这是Node的基本示例。我让它工作 class Node(Base): __tablename__ = 'node' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('node.id')) data = Column(String(50)) children = relationship(

我正在SQL Alchemy中实现一个邻接列表,我正在使用它。这是Node的基本示例。我让它工作

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")

但是,我想强制执行一个约束,
parent\u id!=id
。也就是说,一行不能是它自己的父行。我不知道如何执行这一点。我是否需要使用
@validates
或是否可以在列上设置DB约束。

您可以使用
@validates
或DB约束。约束如下所示:

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'),)

谢谢我可以添加一个@validates方法,但将来我会记住CheckConstraint。