在MongoEngine中创建动态模型

时间:2019-06-09 06:02:43

标签: mongodb mongoengine flask-mongoengine

我是MongoDB和MongoEngine的新手,目前我的文档属于以下类型:

[
    {
        "Question1": "How do you rate the whole restaurant",
        "Rating": [
            "Poor",
            "Average",
            "Good"
        ],
        "next": [
            {
                "Question2": "How do you rate food plates cleanness",
                "Rating": [
                    "Poor",
                    "Average",
                    "Good"
                ]
            },
            {
                "Question3": "How do you rate floor cleanness",
                "Rating": [
                    "Poor",
                    "Average",
                    "Good"
                ]
            }
        ]
    },
    {
        "Question4": "How do you rate food taste",
        "Rating": [
            "Poor",
            "Average",
            "Good"
        ]
    }
]

我正在考虑以以下方式在mongoengine中创建模型:

class Ratings(db.EmbeddedDocument):
    Rating = db.ListField()

class Questions(db.EmbeddedDocument):
    Question = db.StringField()
    rating_type = db.EmbeddedDocumentField(Ratings)

class FeedbackFormTemplate(db.Document):
    pass

以上课程(问题和评分)将用于创建问题和评分。

我想使用类:FeedbackFormTemplate创建文档。但是我对构建模型没有任何想法。

在此方面的任何帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

如果您不受限于上述架构的形状,则建议您执行以下操作:

class QuestionDefinition(EmbeddedDocument):
    question = StringField()
    ratings = ListField(StringField(), default=["Poor", "Average", "Good"])
    next_questions = EmbeddedDocumentListField("self")

class FeedbackFormTemplate(Document):
    questions = EmbeddedDocumentListField(QuestionDefinition)

q1 = QuestionDefinition(question='Food good?')
q2 = QuestionDefinition(question='Plates cleanness?')
q1.next_questions = [q2]

q3 = QuestionDefinition(question='food taste?', ratings=['bad', 'terrible'])
FeedbackFormTemplate(questions=[q1, q3]).save()

print(FeedbackFormTemplate.objects.as_pymongo().first())    # print raw object as stored in mongo

将以下内容存储在mongo中:

{  
   '_id':ObjectId('5cfd5c49caf5e58c7b22f4a8'),
   'questions':[  
      {  
         'question': 'Food good?',
         'ratings': ['Poor', 'Average', 'Good'],
         'next_questions':[  
            {  
               'question': 'Plates cleanness?',
               'ratings': ['Poor', 'Average', 'Good'],
               'next_questions':[]
            }
         ]
      },
      {  
         'question': 'food taste?',
         'ratings': ['bad', 'terrible'],
         'next_questions': []
      }
   ]
}