Search code examples
pythonsql-serverdjango

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

Solution

  • I fixed it by combining all the tips. Thanks to @iklinac

    1. First, I set DEFAULT_AUTO_FIELD = “django.db.models.AutoField”.
    2. 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” to default_auto_field = “django.db.models.AutoField”.
    3. Then deleted all the migration files
    4. First applied the migrations without the new model
    5. Then applied the migrations with the new model. Now there is no error and everything works.