In my database I have a pair of tables (tableA and tableB), both of which have foreign keys referencing the same column ID in tableC. The SQL I was able to use was
SELECT *
FROM tableA
INNER JOIN tableB on tableA.ID=tableB.ID
WHERE tableB.year=2011
The query
SELECT *
FROM tableA
INNER JOIN tableB on tableA.ID=tableB.ID AND tableB.year=2011
Did the same thing
In Django I tried to do this with the code
subquery=tableB.objects.filter(year=2011).values_list(id, flat=True)
results=tableA.objects.filter(id__in=list(subquery))
as suggested in the documentation. I know this is a little different because it only returns columns in tableA, but I only use those anyway. The Django code seemed slow, I think partly because of the set membership test for every row of tableA, which is very large. Is there a way of making this faster in Django without using raw SQL (which I obviously can use if I need to)?
It is slow because it is creating a query that probably looks something like
Like @Udi said, you’d be better off if you could “django”-ize the models by adding the Foreign keys some how. Otherwise, use the RawSQL. That’s what it’s there for.