I'm quite new to Django development. I'm working with a legacy database created with MySQL. Now I'm facing a problems with Django migrations. I have few tables that are using foreign keys for the reference to another table. Now if I allow Django to manage those tables with foreign keys, then Django tries to recreate the foreign key fields during make-migrations and migrate command. Even when the fields are already there. Besides this Django is working perfectly with the database if I don't allow Django to manage those table.
My Code is for table facing error
Models.py
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.db.models.signals import pre_save
from chooseright.utils import unique_slug_generator
class StoreTable(models.Model):
store_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=45, blank=True, null=True)
slug = models.SlugField(max_length=45, blank=True, null=True)
category = models.ForeignKey(CategoryTable, on_delete=models.CASCADE, blank=True, null=True)
brand = models.ForeignKey(BrandTable, models.DO_NOTHING, blank=True, null=True)
class Meta:
managed = True
db_table = 'store_table'
verbose_name = _("Store")
verbose_name_plural = _("Stores")
def __str__(self):
return self.name
Migration Code
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0009_auto_20200820_1258'),
]
operations = [
migrations.RenameField(
model_name='storetable',
old_name='store_name',
new_name='name',
),
migrations.AddField(
model_name='storetable',
name='brand',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='core.BrandTable'),
),
migrations.AddField(
model_name='storetable',
name='category',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.CategoryTable'),
),
]
Traceback when trying to migrate
File "C:\Users\Usama\dev\Django Projects\lib\site-packages\MySQLdb\connections.py", line 259, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1060, "Duplicate column name 'brand_id'")
Now I know that Django is trying to recreate the foreign key field. But since it is a legacy database, I can't understand why it is happening.