一个类从Document扩展,EmbeddedDocument保存失败

时间:2013-04-21 03:04:45

标签: python mongodb document mongoengine

models.py

class User(EmbeddedDocument,Document):
    ''' Store user's info'''
    user_id = IntField(unique = True)
    user_name = StringField(unique =True,primary_key =True,max_length = 256)
    user_secret = StringField(max_length=256)

views.py

def register(request):
    accept = False
    un = request.REQUEST.get('username')
    ps = request.REQUEST.get('password')
    if not un:
        raise ValueError('The given username must be set')
    if not ps:
        raise ValueError('The given password must be set')

    if isUserExistByName(un):
        o='The name has been registered.'
        raise TAUTHException(o)
    else:
        uid = getNextCount(UserCount)
        ps_hash = password_hash(un,ps)
        user = User(user_id = uid,user_name = un,user_secret = ps_hash)
        user.save(cascade = True)
        accept = True

    result = {'accept':accept}
    msg = urlencode(result)
    return HttpResponse(msg)

当我尝试注册用户时,程序运行良好,但mongodb不存储此用户。奇怪的是,如果我将用户改为

class User(Document):
    ''' Store user's info'''
    user_id = IntField(unique = True)
    user_name = StringField(unique =True,primary_key =True,max_length = 256)
    user_secret = StringField(max_length=256)

它运行良好,mongodb存储用户成功。

1 个答案:

答案 0 :(得分:0)

请参阅文档:DocumentEmbeddedDocument

 class mongoengine.EmbeddedDocument(*args, **kwargs)
   A Document that isn’t stored in its own collection.
   EmbeddedDocuments should be used as fields on Documents through the EmbeddedDocumentField field type.

这是因为mongoengine检查文档类型并为不同类型提供不同的逻辑。

但您可以尝试使用force_insert=True进行收藏,或使用mixin来避免文档定义重复:

class UserMixin(BaseDocument):
    ''' Store user\'s info'''
    user_id = IntField(unique = True)
    user_name = StringField(unique =True,primary_key =True,max_length = 256)
    user_secret = StringField(max_length=256)

    def __unicode__(self):
        return self.user_name

class User(Document, UserMixin):
    pass

class UserEmbdebed(EmbeddedDocument, UserMixin):
    pass