2016-09-05 83 views
1

我一直在使用MapField可至今爲:Mongoengine:動態的字段EmbededDocuments作爲值

class Game(EmbeddedDocument): 
    iscomplete = BooleanField() 
    score = IntField() 
    #other not dynamic fields 


class Progress(Document): 
    user = ReferenceField(User, dbref=True) 
    games = MapField(EmbeddedDocumentField(Game)) 
    created_at = DateTimeField() 
    updated_on = DateTimeField() 

我需要遊戲轉換爲ReferenceField。

我想創建一個動態字段/密鑰,但embeddedDocument爲值文件,讓我能有這樣一個文件:

{ 
    "game1": { 
     "iscomplete": true, 
     "score": 23, 
     }, 
    "game2": { 
     "iscomplete": false, 
     "score": 10, 
     } 
} 

爲T這裏反正我可以實現嗎?

回答

1

可以achive,使用dynamic document in mongengine

DynamicDocument文件以同樣的方式爲文檔工作,但任何 數據/屬性設置爲它們也將因此節省

,爲您免除遊戲領域,並且隨後添加您的動態領域遊戲,例如game1,game2等字段,它們將被保存。

class Game(EmbeddedDocument): 
    iscomplete = fields.BooleanField() 
    score = fields.IntField()  

class Progress(DynamicDocument): 
    user = ReferenceField(User, dbref=True) 
    created_at = DateTimeField() 
    updated_on = DateTimeField() 

    p = Progress() 
    p.game1 = Game(iscomplete=True, score=10) 
    p.game2 = Game(iscomplete=False, score=5) 
    p.save()