M
M
meteozond2010-10-11 06:09:41
Django
meteozond, 2010-10-11 06:09:41

How to get rid of duplicate joins on overlapping ForeignKeys in Django?

I noticed something nasty. Let's say there is a model that is linked by two others that have the same ForeignKey.

class File(models.Model):<br/>
&nbsp;&nbsp;&nbsp;&nbsp;#some stuff<br/>
&nbsp;&nbsp;&nbsp;&nbsp;pass<br/>
 <br/>
class ServerFile(models.Model):<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<b>file = models.ForeignKey('File')</b><br/>
&nbsp;&nbsp;&nbsp;&nbsp;#some stuff<br/>
 <br/>
class UserFile(models.Model):<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<b>file = models.ForeignKey('File')</b><br/>
&nbsp;&nbsp;&nbsp;&nbsp;#some stuff<br/>
<br/>
class Link(models.Model): <br/>
&nbsp;&nbsp;&nbsp;&nbsp;user_file = models.ForeignKey('UserFile')<br/>
&nbsp;&nbsp;&nbsp;&nbsp;server_file = models.ForeignKey('ServerFile')<br/>
&nbsp;&nbsp;&nbsp;&nbsp;#some stuff

Accordingly, with list_select_related enabled, we get an additional join on File
SELECT
  `fff_link`.`id`,
  `fff_link`.`user_file_id`,
  `fff_link`.`server_file_id`,
  `fff_userfile`.`id`,
  `fff_userfile`.`file_id` ,
  `fff_file`.`id`,
  `fff_serverfile`.`id`,
  `fff_serverfile`.`file_id`,
  T5.`id`
FROM `fff_link`
  INNER JOIN `fff_userfile`
    ON (`fff_link`.`user_file_id` = ` fff_userfile`.`id`)
  INNER JOIN `fff_file`
    ON (`fff_userfile`.`file_id` = `fff_file`.`id`)

  INNER JOIN `fff_serverfile`
    ON (`fff_link`.`server_file_id` = `fff_serverfile`.` id`)
  INNER JOIN `fff_file` T5
    ON (`fff_serverfile`.`file_id` = T5.`id`)

Maybe someone came across? How to treat?
Refusing to cross is not an option, of course

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FloppyFormator, 2010-10-11
@FloppyFormator

Why treat? In this case JOIN is absolutely adequate.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question