2

模型.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)

视图.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 存储用户成功。

4

1 回答 1

0

请参阅文档:文档EmbeddedDocument

 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您的集合或使用 mixins 来避免文档定义重复:

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
于 2013-04-21T07:05:26.857 回答