我想为文档添加一条记录,然后获取生成的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
答案 0 :(得分:4)
错误的默认值为user_id
。将默认值设置为uuid.uuid4
,这将生成UUID
个对象。
class User(db.DynamicDocument):
user_id = db.UUIDField(primary_key=True, required=True, default=uuid.uuid4)
...