[Django]-Non-primary foreign keys in Django

55đź‘Ť

âś…

Use the to_field and db_column options.

class B(models.Model):
    name = models.ForeignKey(A, to_field="name", db_column="name")

Once you have created the foreign key, you can access the value and related instance as follows:

>>> b = B.objects.get(id=1)
>>> b.name_id # the value stored in the 'name' database column
>>> b.name # the related 'A' instance
👤Alasdair

33đź‘Ť

Django’s models.ForeignKey documentation is not very clear. If you have two models reflected in a database:

class Blockchain(models.Model):
    symbol = models.CharField(max_length=50, primary_key=True, unique=True)

class Wallet(models.Model):
    index = models.AutoField(primary_key=True)
    wallet = models.CharField(max_length=100, null=True)
    blockchain = models.ForeignKey(Blockchain, to_field="symbol", db_column="blockchain")

The “to_field” is actually the name of the field in the Foreign model.

The “db_column” is the name of the field that you want to rename the foreignkey to in the local model

👤jay

Leave a comment