﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
27860	Changing a CharField to a ForeignKey crashes when migrating in PostgreSQL	Daniel Quinn	Mariusz Felisiak	"If I have a model that looks like this:

{{{
class MyModel(models.Model):
    my_field = models.CharField(max_length=128, db_index=True)
}}}

`makemigrations` will create a migration that looks like this:

{{{
        migrations.CreateModel(
            name='MyModel',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('my_field', models.CharField(db_index=True, max_length=128)),
            ],
        ),
}}}

However, if I later change the field to a `ForeignKey`:

{{{
class MyOtherModel(models.Model):
    stuff = models.CharField(max_length=128)

class MyModel(models.Model):
    my_field = models.ForeignKey(""alpha.MyOtherModel"", blank=True)
}}}

`makemigrations` will create this:

{{{
        migrations.AlterField(
            model_name='mymodel',
            name='my_field',
            field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='alpha.MyOtherModel'),
        ),
}}}

...which explodes in PostgreSQL (but not SQLite or MySQL) with this:

{{{
psycopg2.ProgrammingError: operator class ""varchar_pattern_ops"" does not accept data type integer
}}}

The fix (at least for my case) was to manually break up the `AlterField` into separate `RemoveField` and `AddField` steps like this:

{{{
        migrations.RemoveField(
            model_name='mymodel',
            name='my_field',
        ),
        migrations.AddField(
            model_name='mymodel',
            name='my_field',
            field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='alpha.MyOtherModel'),
        ),
}}}

I ran into this on my own GPL project, and the issue history wherein we found and fixed the problem is here: https://github.com/danielquinn/paperless/issues/183"	Bug	closed	Migrations	1.10	Normal	fixed	PostgreSQL		Accepted	1	0	0	0	0	0
