我正在尝试使用名为Portfolios
和PortfolioModels
的两个模型来建模一对多关系。数据模型如下图所示。
我正在使用MongoEngine来生成架构。我到目前为止编写的代码如下所示。
import datetime
from mongoengine import Document, StringField, DateTimeField, ListField, EmbeddedDocument, ReferenceField, \
EmbeddedDocumentField, EmbeddedDocumentListField
from mongoengine import connect
connect('test')
class PortfolioModels(EmbeddedDocument):
PortfolioId = ReferenceField('Portfolios')
ModelName = StringField()
CreateDate = DateTimeField()
LastUpdateDate = DateTimeField(default=datetime.datetime.now)
def save(self, *args, **kwargs):
if not self.CreateDate:
self.CreateDate = datetime.datetime.now()
self.LastUpdateDate = datetime.datetime.now()
return super(PortfolioModels, self).save(*args, **kwargs)
class Portfolios(Document):
PortfolioName = StringField(required=True)
LastUpdateDate = DateTimeField(default=datetime.datetime.now)
RecentActivity = ListField()
PortfolioModels = EmbeddedDocumentListField('PortfolioModels')
def __str__(self):
return self.PortfolioName
if __name__ == '__main__':
a = Portfolios(
PortfolioName="Best Buy Visa Portfolio",
RecentActivity=[
"Data Refreshed by JV on 04-07-2015",
"Model Updated by SM on 04-12-2015"
]
)
b = PortfolioModels(
ModelName="Baseline Model"
)
a.save()
代码为我提供了这样的输出。
{
"Id": ObjectId("34545fggdeesrhygsdf"),
"PortfolioName": "General Motors MasterCard Portfolio",
"LastUpdateDate": "2015-04-23T18:25:43.511Z",
"RecentActivity": [
"Data Refreshed by JV on 04-07-2015",
"Model Updated by SM on 04-12-2015"
],
"PortfolioModels": []
}
预期输出如下所示。我错过了什么。
[
{
"Id": "12345",
"PortfolioName": "Best Buy Visa Portfolio",
"LastUpdateDate": "2015-04-23T18:25:43.511Z",
"RecentActivity": [
"Data Refreshed by JV on 04-07-2015",
"Model Updated by SM on 04-12-2015"
],
"PortfolioModels": [
{
"Id": "24079",
"PortfolioId": "12345",
"ModelName": "Baseline Model",
"CreateDate": "2015-04-23T18:25:43.511Z",
"LastUpdateDate": "2015-04-23T18:25:43.511Z"
},
{
"Id": "83623",
"PortfolioId": "12345",
"ModelName": "Baseline Model Old",
"CreateDate": "2013-06-23T18:25:43.511Z",
"LastUpdateDate": "2013-08-23T18:25:43.511Z"
}
]
},
{
"Id": "08938",
"PortfolioName": "General Motors MasterCard Portfolio",
"LastUpdateDate": "2015-04-23T18:25:43.511Z",
"RecentActivity": [
"Data Refreshed by JV on 04-07-2015",
"Model Updated by SM on 04-12-2015"
],
"PortfolioModels": []
}
]
答案 0 :(得分:0)
试
PortfolioModels = ListField(EmbeddedDocumentField(PortfolioModels));
或
PortfolioModels = EmbeddedDocumentListField(PortfolioModels)
只需删除单引号,并确保您放入EmbeddedDocumentListField的参数是一个对象(类),但不是E mbeddedDocument的名称(字符串)