在Django中使用mongoengine。无法将文档实例保存到数据库

时间:2015-05-05 17:28:00

标签: python django mongodb mongoengine

我正在尝试创建新文档并将其保存到数据库中。 Mongo中的数据库是自动创建的,但没有保存任何条目。我在我的代码中尝试做的是:

lesson = Lesson()
lesson.group = Group(group_name='KP-32')
lesson.teacher = Teacher(teacher_name='Vasia')
lesson.room = Room(room_number=32, building_number=323)
lesson.subject = Subject(subject_code=03321, subject_name='Math', hours=33)
lesson.save()
ls = []
for lesson in Lesson.objects:
    ls.append(lesson)

但是当我尝试显示ls时,我只在视图中显示(显示ls): id主题教师组室(引用名称???)并且没有任何内容存储到数据库中。 希望听到我的问题的一些解决方案,并提前感谢。

设置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy',
    }
}
mongoengine.connect('jack', host='127.0.0.1', port=27017)

AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'

模型

from mongoengine import *

    class Room(EmbeddedDocument):
        room_number = IntField(default=0)
        building_number = IntField(default=0)
        capacity = IntField(default=0, required=False)

        def __unicode__(self):
            return smart_unicode("Room #%d" % self.room_number)


    class Teacher(EmbeddedDocument):
        teacher_name = StringField(max_length=60)
        phone = StringField(max_length=15, required=False)
        email = StringField(required=False)

        def __unicode__(self):
            return smart_unicode(self.teacher_name)


    class Subject(EmbeddedDocument):
        subject_code = IntField()
        subject_name = StringField(max_length=60)
        hours = IntField(required=False)

        def __unicode__(self):
            return smart_unicode(self.subject_name)


    class Group(EmbeddedDocument):
        group_name = StringField(max_length=20)
        specialization = StringField(max_length=60, required=False)
        student_count = IntField(required=False)

        def __unicode__(self):
            return smart_unicode(self.group_name)


    class Lesson(Document):
        subject = EmbeddedDocumentField(Subject)
        teacher = EmbeddedDocumentField(Teacher)
        group = EmbeddedDocumentField(Group)
        room = EmbeddedDocumentField(Room)
        attendance = IntField()

        def __unicode__(self):
            return smart_unicode("Lesson #%d" % self.id)

1 个答案:

答案 0 :(得分:0)

执行此行时会创建数据库

mongoengine.connect('jack', host='127.0.0.1', port=27017)

它也适合我。

你能为我打印一下这个输出:

ls[0].__dict__