2016-01-15 76 views
1

我有一個MySQL表,在SQLAlchemy的定義與結構如下:外鍵相同的表中的SQLAlchemy

class User(Base): 
    __tablename__ = 'user' 
    __table_args__ = {'mysql_charset': 'utf8', 'mysql_engine': 'InnoDB'} 
    id = Column(Integer, primary_key=True) 
    handle = Column(String(250), nullable=False) 
    owned = Column(Boolean(), default=False) 
    owner_id = Column(Integer, ForeignKey("user.id"), nullable=True, default=null) 
    current_price = Column(Integer, nullable=False, default=1) 
    balance = Column(Integer, nullable=False, default=0) 

我希望有一個關係,以便owner_id可以爲空,或者如果它設置好,在同一個表中引用一個有效的user.id。

我不太瞭解sqlalchemy關係的東西足以能夠做到這一點。這頁http://docs.sqlalchemy.org/en/latest/orm/relationship_persistence.html頂部的特殊東西似乎表明這是可能的,但我無法弄清楚。

我希望再能以添加用戶,如:

u1 = User(handle="bob") 
u2 = User(handle="jim", owner=u1) 

感謝您的幫助!

我應該補充說,sqlalchemy沒有問題做正確的FOREIGN KEY約束CREATE TABLE,我可以手動INSERT數據到服從規則,因爲我希望他們在MySQL中,它只使用sqlalchemy模型失敗。

編輯:解決

'默認= NULL' 上owner_id是造成問題的某些原因。有用的文檔在這裏:http://docs.sqlalchemy.org/en/rel_1_0/orm/self_referential.html,並從該頁面在這裏的代碼示例:http://docs.sqlalchemy.org/en/rel_1_0/orm/examples.html#examples-adjacencylist

對於谷歌的蜘蛛機器人,我在這個過程中有錯誤是:

sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`twitfriends`.`tree`, CONSTRAINT `tree_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `tree` (`id`))') [SQL: u'INSERT INTO tree (parent_id, name) VALUES (%s, %s)'] [parameters: (<sqlalchemy.sql.elements.Null object at 0x7fe7e8c468d0>, 'rootnode')] 

而且

ArgumentError: Node.next and back-reference Node.prev are both of the same direction <symbol 'ONETOMANY>. Did you mean to set remote_side on the many-to-one side ? 
+0

對於任何發現這種情況的人來說,停止上述代碼工作的東西是owner_id字段上的'default = null'! – mozboz

+0

錯誤是:它生成了以下錯誤:sqlalchemy.exc.IntegrityError:(_mysql_exceptions.IntegrityError)(1452,'無法添加或更新子行:外鍵約束失敗('db'.'tree',CONSTRAINT'tree_ibfk_1 FOREIGN KEY('parent_id')參考'''''''''''''')''[SQL:u'INSERT INTO樹(parent_id,name)VALUES(%s,%s)'] [參數:(,'rootnode')] – mozboz

回答

1

由於User只有一個外鍵,我希望sqlalchemy自動計算出連接條件。您還可以添加backref,這樣您就可以獲得關係的另一面。

class User(Base): 
    ... 
    owner = relationship('User', remote_side=['id'], backref='owned_users') 

Docs

例。

u1 = User(handle="bob") 
u2 = User(handle="jim", owner=u1) 
print u2.owned_users[0] == u1 
# True 
+0

這兩個失敗: sqlalchemy.exc.ArgumentError:User.owner和反向引用User.owned_users都是相同的方向符號('ONETOMANY' )。你是否想要在多方面設置remote_side? – mozboz

+0

這導致我,但它似乎並不工作:http://stackoverflow.com/questions/12872873/one-to-one-self-relationship-in-sqlalchemy – mozboz

+0

@mozboz請參閱編輯 –