Django relation on two database columns
I am using django to interface with an existing database that I have no control over.
The database frequently uses multiple columns for making relations and has uniqueness over all of those columns.
The django inspectdb
model generator correctly identified these as unique_together = (('foo', 'bar'), ('foo', 'bar'),)
, resulting in the following model:
class A(models.Model):
foo = models.IntegerField(db_column='FOO', primary_key=True)
bar = models.IntegerField(db_column='BAR')
class Meta:
managed = False
db_table = 'A'
unique_together = (('foo', 'bar'), ('foo', 'bar'),)
Now there is another table whose entries relate to that table on both columns. When querying using SQL I would relate them like this:
SELECT * FROM A LEFT JOIN B ON A.foo = B.foo AND A.bar = B.bar
However inspectdb
failed to correctly map the two columns being used in a relating table:
class B(models.Model):
foo = models.OneToOneField(A, models.DO_NOTHING, db_column='A', primary_key=True)
bar = models.ForeignKey(A, models.DO_NOTHING, db_column='A')
The above is what it generated, however in reality it is a many-to-one relationship to table A. This then causes an error at runtime because the column bar
in table A
is not unique.
Can I somehow define this relationship in a django model?
And how do I query this efficiently so that django generates a JOIN
expression with two conditionals?