Search code examples
pythondjangodjango-modelsforeign-keys

How can I change the db_column name of foreign key in Django?


How can I change db_column of Foreign Key in Django?


class A(models.Model):
    it_id = models.CharField('IT ID', max_length=10)

class B(models.Model):
    it_id = models.ForeignKey('A', related_name='item', on_delete=models.PROTECT, db_column='it_id')

when I call objects,

>>> B.objects.all().values()
<QuerySet [{'it_id_id'}:'xxx']>

It is 'it_id_id'....

How can I change 'it_id' from 'it_id_id'?


Solution

  • This has nothing to do with the name of the database column, but with the name of the Django field. Django will automatically add a …_id suffix for ForeignKeys that then stores the primary key of the referenced object. It thus makes no sense that a ForeignKey has a name that ends with a …_id. For more information, see the _id suffix antipattern.

    You thus can change your model to:

    class B(models.Model):
        it = models.ForeignKey(
            'A',
            related_name='item',
            on_delete=models.PROTECT
        )

    If you do not want to do that, you can fetch the value for the it_id through an alias with:

    from django.db.models import F
    
    B.objects.values(it_id=F('it_id_id'))