Error when I change id to UUID

Hi everybody,

I have this model:

class Usuarios(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    website = models.URLField(max_length=200, blank=True, default="")
.
.
.
.

I did makemigrations and migrate but then I wanted to use UUID instead id, so I changed the model to this:

class Usuarios(models.Model):
    id = models.UUIDField(primary_key = True,default = uuid.uuid4, editable = False)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    website = models.URLField(max_length=200, blank=True, default="")
.
.
.
.

But I get the next error:

django.db.utils.ProgrammingError: column "id" is of type bigint but expression is of type uuid
LINE 1: ...uineo", "picture", "created", "modified") VALUES ('1c99de28-...
                                                             ^
HINT:  You will need to rewrite or cast the expression.

I delete migrations and did again makemigrations and migrate, but I have the same error.

Someone who knows why this happens or I have to delete my database even though I have information that I do not want to delete?

Changing the primary key in Django is problematic.

If I had to do this, I’d do it one of two ways:

  • Directly at the database layer.
    • Create and populate the UUID field
    • Drop the id column
    • Assign the new UUID field as the primary key

-or-

  • Create a new model with the UUID as the new primary key
  • Copy the data to the new model
  • Drop the original model
  • Rename the new model to the same name as the original.

Note that it’s only this easy if there are no other tables that have foreign key references to this table. If there are, you’re going to need to change those foreign key references as well.

If there’s not much data you’re concerned with, the simplest process is to drop and recreate the table.

It’s up to you to decide which is going to be the easiest to do.

2 Likes

What I would do (and have done) was change from bigint to varchar and from varchar to uuid. You need to first change the id field to CharField, change all ids from numbers to hex uuids, and then make a migration from varchar to uuid, casting all ids to UUID.