gpt4 book ai didi

python - 访问 Mongo 文档的 id 字段引发 "TypeError: need one of hex, bytes, bytes_le, fields, or int"

转载 作者:可可西里 更新时间:2023-11-01 09:29:54 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于python - 访问 Mongo 文档的 id 字段引发 "TypeError: need one of hex, bytes, bytes_le, fields, or int",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32286736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com