UUID('...')不可JSON序列化 [英] UUID('...') is not JSON serializable

查看:391
本文介绍了UUID('...')不可JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I get this error when i try to pass the UUID attribute to url parameter.

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}))

model.py

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

有什么建议吗?

推荐答案

在Django上有关于此问题的故障单,但是python文档提供的所谓复杂编码器自定义功能可以为您提供帮助。

There is a bug ticket on Django regarding this issue however a custom so called 'complex encoder' by python docs can help you.

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)

现在我们做了这样的事情

Now if we did something like this

json.dumps(my_object, cls=UUIDEncoder)

您的uuid字段应进行编码。

Your uuid field should be encoded.

这篇关于UUID('...')不可JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆