[Fixed]-Cannot cast type integer to uuid

36👍

So, basically you started the model without an explicit primary key. So you got a free AutoField and now want them to be UUID’s.

As you can see, Postgres (or any db I know of) doesn’t allow changing integers to UUIDs. So you need do a few migrations to get the state you want to:

First add the uuid field as a normal field with a different name:

import uuid
from django.db import models

class MyModel(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, unique=True)

Run makemigrations and migrate.

Now make it primary key:

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

This should generate a migration that removes the id field and makes uuid primary key (makemigrations and migrate again).

And finally (if you still want to):

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

Honestly, I don’t know if this goes OK, you may have to adjust the generated migration. In either case, you’ve should now be where you want to be.

Leave a comment