UUID('…') is not JSON serializable

前端 未结 4 1360
生来不讨喜
生来不讨喜 2020-12-05 23:19

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

urlpatterns = [
    url(r\'^historia-clinica/(?P[W\\d\\-]+)/$\', ClinicH         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 23:52

    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)
    

    Your uuid field should be encoded.

提交回复
热议问题