2014-01-15 62 views
0

我有2個模型具有死 - 簡單的一對多關係。我試圖將其中一個查詢的結果分配給另一個實體,但我不知道該怎麼做。這是代碼:Peewee Python ORM:將查詢結果分配給ForeignKeyField

從2類主要的類繼承,並具有同樣的__init__方法重載

class Bot(MySQLDatabase, ClientXMPP): 
    room = ForeignKeyField(Room) 

在某些時候,我查詢和嘗試分配:

def __init__(self, ..., ..., room): 
    DBConnection.connect() 

    self.room = Room.get(...) 
    self.save() 

但拋出我這個例外:

Traceback (most recent call last): 
    File "main.py", line 25, in <module> 
    xmpp = Bot(..., ..., room) 
    File "/home/.../bot.py", line 29, in __init__ 
    self.room = room 
    File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 724, in __set__ 
    instance._data[self.att_name] = value.get_id() 
TypeError: 'NoneType' object does not support item assignment 

我剛開始使用這個庫,所以thi這可能是由於對文檔的誤解。

+0

可不可以給你的模型尤其是教室的更詳細?否則,我敢打賭你已經知道[this](http://peewee.readthedocs.org/en/latest/peewee/querying.html#looking-at-some-simple-queries) – hepidad

+0

我正在更新帖子以添加更多信息。我不認爲Room的結構是相關的(畢竟它是一個帶有屬性的簡單類),但是由於我使用的是帶有重載的__init__方法的多重繼承,看起來問題來自於此。 –

+0

對不起,我認爲你需要在這裏更清楚地發佈你的模型。無論如何,嘗試簡單查詢peewee與[這個文件](http://peewee.readthedocs.org/en/latest/peewee/querying.html#looking-at-some-simple-queries)。 – hepidad

回答

1

我知道這是一個老問題,但如果其他人得到這個錯誤,我發現這個鏈接:Peewee models perform initialization on startup,因此你必須在任何peewee模型構造函數中調用super。

所以,

def __init__(self, ..., ..., room): 
    DBConnection.connect() 

    self.room = Room.get(...) 
    self.save() 


將成爲:

def __init__(self, ..., ..., room): 
    super(Bot, self).__init__() 
    DBConnection.connect() 
    self.room = Room.get(...) 
    self.save() 
+0

正確,謝謝你提交這個答案 – coleifer