'UUID Is not JSON Serializable (dumpdata)

I'm having an issue with the command dumpdata. I'm using django-uuidfield as primary key for a few of my models, however; whenever I try to run dumpdata, I run into the error

TypeError: UUID('...') is not JSON serializable.

I found that inside of Django's DjangoJSONEncoder class that it doesn't check for the UUID object and will go to the default() of the parent class which throws the exception.

When I added a check, it seemed to work properly without any errors or warnings.

I'm not sure if that's a bug or I'm doing something wrong.

Note:

I didn't change any code inside django-uuidfield.

Thanks.

Edit:

The dumpdata works for another model where the uuidfield is not set to auto. The one that doesn't work has the uudfield set to auto.



Solution 1:[1]

In my models.py:

import uuid

In my model:

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

and to solve this problem, I use this function write in MyUser:

def user_id(self):
    return self.id.__str__()

As the TypeError try you that type UUID is not JSON serializable,

so you should use string instead.

Hope it will help you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Henry