Column 'tbl1.id' is not the same data type as referencing column 'tbl2.field_id' in foreign key 'tb1_field_id_tbl2_id'
I have a problem with migrations. I'm using database which was created with old Django version 1.4 in new application with Django version >5. The problem is that old Django is using different data type for primary key field (AutoField - int in database). So in database datatype of old django's primary key is "int" and in the new Django datatype is "bigint". I've created new model with Foreign Key to old model and now I'm facing an error:
Column 'tbl1.id' is not the same data type as referencing column 'tbl2.field_id' in foreign key 'tb1_field_id_tbl2_id'
How can I solve this problem?
Only thing that help is to assign db_constraint=True in the models.ForeignKey field. But I don't want have this risk.
Things that I've already tried:
- Change DEFAULT_AUTO_FIELD to django.db.models.AutoField
- Explicitly set id of foreign key table to AutoField. To much dependencies on this table, so it crashes on other relations.
- Explicitly map to certain field
to_field="id"
- Set
db_constraint=False
- it helps but not the best solution. - Made new migration for new model with AutoField. It seems like Django still refer to
bigint
for foreign key table
Either migrate old models to bigint
or
Set DEFAULT_AUTO_FIELD
to
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
Following is still default for old projects but for new projects it is set to BigAutoField
as documented
Starting with 3.2 new projects are generated with DEFAULT_AUTO_FIELD set to BigAutoField.
I fixed it by combining all the tips. Thanks to @iklinac
- First, I set
DEFAULT_AUTO_FIELD = “django.db.models.AutoField”
. - Then in each application in the apps.py file in the application classes, I changed the default_auto_field field from
default_auto_field = “django.db.models.BigAutoField”
todefault_auto_field = “django.db.models.AutoField”
. - Then deleted all the migration files
- First applied the migrations without the new model
- Then applied the migrations with the new model. Now there is no error and everything works.