While working on the (badly designed) legacy db that brought me here with the original question of this thread, I noticed another issue that I wasn’t sure how to handle with the migration to Django.
Apparently (for reasons that are beyond me), there are some tables that have a fk to a certain table, but which is also used to JOIN other tables in some queries.
For example: let’s say there’s table_a
, table_b
, and table_c
.
table_c
has a field, a_id
, which is a foreign key to table_a
.
However, there are also some queries which are being performed on the db that look something like:
select table_b.*, table_c.some_field from table_b left join table_c on table_c.a_id = table_b.id
Of course, it becomes pretty hard to model this query with the ORM if the models look like this:
class TableA(Model):
# ...
class Meta:
managed = False
db_table = '"schema1"."table_a"'
class TableB(Model):
# ...
class Meta:
managed = False
db_table = '"schema1"."table_b"'
class TableC(Model):
a = ForeignKey(TableA)
some_field = ...
# ...
class Meta:
managed = False
db_table = '"schema1"."table_c"'
Have you ever found yourself in such a situation?
This is how I was able to work around this: I created a proxy model for TableC
, which looks like this:
class TableCWithReferenceToTableB(TableC):
_a = ForeignKey(TableB, db_constraint=False, db_column="a_id")
class Meta:
managed = False
proxy = True
db_table = '"schema1"."table_c"'
Now, I am able to use the ORM like this:
TableB.objects.filter(tablecwithreferencetotableb__some_field="some_condition")
Which generates a query similar to
select * from table_b inner join table_c on table_c.a_id = table_c.id where table_c.some_field = "some_condition"
How does this solution look? Do you think there’s a better way to go around this design flaw in the db?