Non-primary foreign keys in Django
Question:
I have two tables from a legacy database that I want to access from a Django site. They look like this:
Table A
id (int, primary key)
name (string, unique)
...
Table B
id (int, primary key)
name
record_date
(name, record_date are unique together)
...
How do I tell my Django model that Table A
has a one-to-many relationship with B
on A.name=B.name
? The regular ForeignKey
relationship would require that B
use A.id
instead of name
, but I can’t modify the structure of the existing legacy database.
Answers:
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
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
I have two tables from a legacy database that I want to access from a Django site. They look like this:
Table A
id (int, primary key)
name (string, unique)
...
Table B
id (int, primary key)
name
record_date
(name, record_date are unique together)
...
How do I tell my Django model that Table A
has a one-to-many relationship with B
on A.name=B.name
? The regular ForeignKey
relationship would require that B
use A.id
instead of name
, but I can’t modify the structure of the existing legacy database.
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
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