SQLAlchemyで非常に奇妙な問題が発生しました。自己参照(隣接リスト関係)のモデルがあります。SQLAlchemyチュートリアルからモデル(ノード)をコピーしただけです。モデルのコードは次のとおりです。
class Node(Base):
__tablename__ = 'nodes'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('nodes.id'))
parent = Column(Unicode(50))
children = relationship('Node',
cascade="all", #tried to remove this
backref=backref("parent", remote_side='Node.id'),
collection_class=attribute_mapped_collection('data'), #tried to remove this as well
)
コントローラ内で問題を再現しましたが、このテストも実行しました(もちろん、環境を完全にロードした後)。
parent = Node()
parent.id = 1
parent.parent_id = None
parent.name = 'parent'
Session.add(parent)
child = Node()
child.id = 20
child.parent_id = 1
child.name = 'child'
Session.add(child)
Session.commit()
上記のコードは問題なく機能します(変更は正常にコミットされ、DBに反映されます)。
この問題は、parent
ノードのidを0に変更すると(child
それに応じてのparent_idを0に変更すると)発生します。次に、次の例外が発生します。
......
File "C:\Python26\Lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
sqlalchemy.exc.IntegrityError: (IntegrityError) (1452, 'Cannot add or update a child row: a
foreign key constraint fails (`db`.`nodes`, CONSTRAINT `nodes_ibfk_1` FOREIGN KEY
(`parent_id`) REFERENCES `nodes` (`id`))') 'INSERT INTO nodes (id, parent_id, name) VALUES
(%s, %s, %s)' (20, 0, 'child')
驚いたことに、この値( 'sidnode
とchild
's parent_id)を0( -5、1、150)以外に変更すると、エラーはなくなります。
明らかな何かが欠けていますか?自己参照の整数ID列に0を割り当てることはできませんか?
ありがとう!