I'm working in a project where I need to migrate an IntegerField to a ForeingKey to make it easier to do requests as: SKU_name, SKU_description, etc..
My models.py file has:
class BasketTable(models.Model):
"""Basket table."""
SKU_Id = models.IntegerField(default=0, verbose_name="ID do SKU")
Quantity = models.IntegerField(default=0, verbose_name="Quantidade")
I'm trying to change SKU_Id to SKU field name, setting:
SKU = models.ForeignKey(SKUTable, db_column='Id', to_field='Id', null=True, verbose_name="ID do SKU")
My SKU_Id field has unique=True as needed according Django documentation.
So, after this change, I run python manage.py makemigrations command which results in:
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.RemoveField(
model_name='baskettable',
name='SKU_Id',
),
migrations.AddField(
model_name='baskettable',
name='SKU',
field=models.ForeignKey(db_column='Id', null=True, on_delete=django.db.models.deletion.CASCADE, to='products.SKUTable', to_field='Id', verbose_name='ID do SKU'),
),
]
So, I changed this migration file to:
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.AlterField(
model_name='baskettable',
name='SKU_Id',
field=models.IntegerField(db_column='Id')
),
migrations.RenameField(
model_name='baskettable',
old_name='SKU_Id',
new_name='SKU',
),
migrations.AlterField(
model_name='baskettable',
name='SKU',
field=models.ForeignKey(db_column='Id', null=True, on_delete=django.db.models.deletion.CASCADE,
to='products.SKUTable', to_field='Id', verbose_name='ID do SKU'),
),
]
And after this, I run the command python manage.py migrate to save these changes.
The migration works and the data SKU and SKU_id can be accessed using list_display in my Admin, but when I try to access data as SKU_name or any other field, I got this error message:
SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'cil.models.BasketTableAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'SKU_Name', which is not a callable, an attribute of 'BasketTableAdmin', or an attribute or method on 'cil.BasketTable'.
System check identified 1 issue (0 silenced).
I hope that someone can make clear what I'm doing wrong when I try to get other table fields using the list_display or any other get function from models.
I used the following information to get here:
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey.to_field
Edit 1:
I cleaned the code a little bit more.
One possible solution that I found is not change the name of the field and don't use db_column, instead, use to_field='destination_key_field'.
SKU = models.ForeignKey(SKUTable, to_field='Id', null=True, verbose_name="ID do SKU")
It is important to have null=True when working with this change.