python - UUID ('...' ) 不是 JSON 可序列化的

标签 python django uuid

当我尝试将 UUID 属性传递给 url 参数时出现此错误。

urlpatterns = [
    url(r'^historia-clinica/(?P<uuid>[W\d\-]+)/$', ClinicHistoryDetail.as_view(), name='...'),
]

views.py

class ClinicHistoryDetail(...):
     ...
     my_object = MyModel.objects.create(...)
     ...
     return redirect(reverse('namespace:name', kwargs={'uuid' : my_object.id}))

模型.py

class MyModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ...

有什么建议吗?

最佳答案

在 Django 上有一个关于这个问题的错误票,但是 python 文档的一个自定义的所谓的“复杂编码器”可以帮助你。

import json
from uuid import UUID


class UUIDEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, UUID):
            # if the obj is uuid, we simply return the value of uuid
            return obj.hex
        return json.JSONEncoder.default(self, obj)

现在如果我们做这样的事情

json.dumps(my_object, cls=UUIDEncoder)

你的 uuid 字段应该被编码。

关于python - UUID ('...' ) 不是 JSON 可序列化的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36588126/

相关文章:

r - 在 R 中生成 UUID 向量的更快方法

python - 具有与信息增益不同的分割标准的决策树

Python 3.5 CSV.reader 不返回任何行

iphone - 如何将 UUID 存储为 int

python - Postgre/SQLAlchemy UUID 插入但无法比较

python - Django 无法访问 raw_post_data

python - 谷歌应用引擎( python ): TemplateSyntaxError: 'for' statements with five words should end in 'reversed'

python - 堆叠矩阵以创建一个矩阵,其中父矩阵映射的位点作为 block 对角线

python - Django Model 类中的函数不接受 self 参数?

python - 为什么我在 django 上的 html 文件上出现 endfor 加载错误?