2016-06-28 83 views
0

簡化,我有2個文件對象:ResourceCable保存的參考場mongoengine

class Cable(db.Document): 
    _id = db.ObjectIdField() 
    socket = db.EmbeddedDocumentField(Socket) 

class Resource(db.Document): 
    _id = db.StringField() 
    cable = db.ReferenceField('Cable') 

兩個文件都已經在分貝,但在資源電纜字段設置爲null

@resources.route('/<r_id>/add_cabling', methods=['GET']) 
def set_connector(r_id): 
    r = Resource.objects(id=r_id).get() 
    c = Cable.objects().first() 
    r.cable=c 
    r.save() 
    return jsonify(r) 

所以我通過實例文檔Cable來的Resource實例,然後save()。 錯誤,我得到的是這樣的:

ValidationError: ValidationError (Resource:res01) (A ReferenceField only accepts DBRef or documents: ['cable'])

我不明白,因爲其實我傳遞文檔本身

回答

0

與此變通辦法通過原稿的DBRef和它的作品嚐試。

@resources.route('/<r_id>/add_cabling', methods=['GET']) 
def set_connector(r_id): 
    r = Resource.objects(id=r_id).get() 
    c = Cable.objects().first() 
    c.save() #revalidate here 
    r.cable=c.to_dbref() 
    r.save() 
    return jsonify(r) 

有必要查詢到的對象上再次執行save()操作,以獲得DBRef否則會拋出這個錯誤:

OperationError: Only saved documents can have a valid dbref