I’m encountering an issue while migrating my Django project from SQLite to PostgreSQL. I had previously set the id field to UUID in SQLite, but now when applying the migration in PostgreSQL, I receive the following error:
`django.db.utils.ProgrammingError: cannot cast type bigint to uuid
LINE 1: …ompany_company” ALTER COLUMN “id” TYPE uuid USING “id”::uuid
^
my models
class Company(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.OneToOneField(User, on_delete=models.CASCADE)
class Job(models.Model):
BEGINNER = 'Beginner'
MID = 'Mid'
EXPERT = 'Expert'
LEVEL_CHOICES = [
(BEGINNER, 'Beginner'),
(MID, 'Mid'),
(EXPERT, 'Expert'),
]
user = models.ForeignKey(User, on_delete=models.CASCADE)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
`
I initially developed my Django project using SQLite and set the id field of the Company model to UUID. Now that I am migrating the database to PostgreSQL, I need to update the id field to UUID in the PostgreSQL schema.
Details:
1.Current Migration Code:
# Generated by Django 4.2.7 on 2024-04-26 22:25
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('company', '0002_initial'),
]
operations = [
migrations.AlterField(
model_name='company',
name='id',
field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
),
]
2.Migration Error Message:
psycopg2.errors.CannotCoerce: cannot cast type bigint to uuid
LINE 1: ...ompany_company" ALTER COLUMN "id" TYPE uuid USING "id"::uuid
^
I have attempted to:
Use ALTER COLUMN in the migration file to cast the type, but encountered issues with type coercion.
Add a temporary UUID field and migrate data into it before dropping the original id field, but still faced challenges.
Nyuydine Bill leynyuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.