访问Mongo文档的id字段会引发“TypeError:需要hex,bytes,bytes_le,fields或int之一”

时间:2015-08-29 13:46:24

标签: python mongodb flask flask-mongoengine

我想为文档添加一条记录,然后获取生成的id。但是,当我尝试访问TypeError: need one of hex, bytes, bytes_le, fields, or int时,收到错误user_id。为什么我会收到此错误?

class User(db.DynamicDocument):
    user_id = db.UUIDField(primary_key=True, required=True, default=uuid.UUID)
    ...

user = User().save()
user_id = user.user_id
File "views.py", line 15, in post
    user = User().save()
  File "/usr/local/lib/python2.7/dist-packages/mongoengine/base/document.py", line 96, in __init__
    setattr(self, key, value)
  File "/usr/local/lib/python2.7/dist-packages/mongoengine/base/document.py", line 188, in __setattr__
    super(BaseDocument, self).__setattr__(name, value)
  File "/usr/local/lib/python2.7/dist-packages/mongoengine/base/fields.py", line 123, in __set__
    value = value()
  File "/usr/lib/python2.7/uuid.py", line 129, in __init__
    raise TypeError('need one of hex, bytes, bytes_le, fields, or int')
TypeError: need one of hex, bytes, bytes_le, fields, or int

1 个答案:

答案 0 :(得分:4)

错误的默认值为user_id。将默认值设置为uuid.uuid4,这将生成UUID个对象。

class User(db.DynamicDocument):
    user_id = db.UUIDField(primary_key=True, required=True, default=uuid.uuid4)
    ...