2011-04-20 3 views
0

SQLAlchemy에서 매우 이상한 문제가 발생했습니다. 자체 참조하는 모델이 있습니다 (인접 목록 관계). 간단히 SQLAlchemy 튜토리얼에서 모델 (Node)을 복사했다. 여기에 모델의 코드입니다 :SQLAlchemy 자체 참조 테이블에서 기본 인덱스로 0을 가질 수 없습니까?

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

위의 코드는 잘 작동합니다 : 내 컨트롤러 내에서 문제를 재현하지만, (완전 물론 내 환경을로드 한 후) 나는 또한이 테스트를 실행

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 
    ) 

(변경 사항이 성공적으로 커밋되어 DB에 반영됩니다).

parent 노드의 ID를 0으로 변경하고 그에 따라 child의 parent_id를 0으로 변경하면 문제가 발생합니다. 이 값합니다 (node의 ID 및 child의 PARENT_ID) 아무것도하지만 0 (-5, 1, 150)에 오류하게 변경, 놀랍게도

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

: 다음, I는 다음의 예외를 얻을 가버 리다.

나는 분명한 뭔가를 놓치고 있습니까? 자체 참조 정수 ID 열에 0을 할당 할 수 있습니까?

감사합니다.

+0

일부 연구에 따르면 값 0을 ID로 삽입하면 MySQL은 내 ID 열을 시퀀스로보고이를 향상시킵니다. 따라서 아무 것도 없으면 1로 설정합니다. id가 6 인 이전 행을 입력하면 id가 0 인 새 행을 삽입하면 새 행의 id가 7이됩니다. 왜 이런 일이 일어나고이 문제를 해결할 수있는 방법이 있습니까? – Raiders

+0

분명히 내 모든 Column (Integer, primary_key = True) 열은 기본적으로 AUTO_INCREMENT입니다. 이 기본 옵션을 취소하려면 어떻게해야합니까? (autoincrement = False를 명시 적으로 전달하는 것 외에는? – Raiders

답변

0

MySQL은 명시 적으로 NULL 또는 0을 전달할 때 생성 된 ID를 사용합니다. 인수로 autoincrement=FalseColumn에서 무시할 수있는 AUTO_INCREMENT으로 전달하십시오.