Note: I've simplified the call slightly by using a different part of the
data model than what I'm really after, but it makes it clearer I think.
This can preferably be done with select_related() in this example but
the real query I'm after cannot since the FK is in the next table over.
Anyway...
This correctly adds "page_item" to the FROM clause by using extra().
Notice I'm not yet referencing a related table in the filter() clause.
In [29]: Page.objects.extra(
tables=['page_item'],
where=['page_item.page_id=page_page.id'])
.filter(template__id='1')._get_sql_clause()
Out[29]:
(['`page_page`.`id`',
'`page_page`.`number`',
'`page_page`.`title`',
'`page_page`.`template_id`',
'`page_page`.`description`'],
' FROM `page_page` , `page_item` WHERE page_item.page_id=page_page.id
AND (`page_page`.`template_id` = %s)',
['1'])
But adding the related table in the filter() clause breaks the extra()
tables and "page_item" disappears...
In [30]: Page.objects.extra(
tables=['page_item'],
where=['page_item.page_id=page_page.id'])
.filter(template__name='Default Template')
._get_sql_clause()
Out[30]:
(['`page_page`.`id`',
'`page_page`.`number`',
'`page_page`.`title`',
'`page_page`.`template_id`',
'`page_page`.`description`'],
' FROM `page_page` INNER JOIN `page_template` AS `page_page__template`
ON `page_page`.`template_id` = `page_page__template`.`id` , `page_item`
WHERE page_item.page_id=page_page.id AND (`page_page__template`.`name` =
%s)',
['Default Template'])
I'm going to try a workaround in my real query by shifting my query over
to the next related table so select_related() can follow the FK
backwards but this requires my query to be broken into multiple queries.
I thought this was worth pointing out, though. I would expect that
having a related table in the filter shouldn't drop the extra tables.
-Rob