﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
13017	generic relation generates needless join	MS	nobody	"I have an generic relation, and tries to do some database queries with this relation. 
When looking at the generated sql query i saw, that double joins are created. This happens 
because generic relations are based on m2m table with a missing database table.

An example for the model:
{{{
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class GenericTest(models.Model):
    contentType = models.ForeignKey(ContentType)
    objectId = models.PositiveIntegerField()
    contentObject = generic.GenericForeignKey('contentType', 'objectId')

class RefTest(models.Model):
    generic = generic.GenericRelation(GenericTest, content_type_field='contentType', object_id_field='objectId')
    testdata = models.PositiveIntegerField()
}}}
the query:

{{{GenericTest.objects.filter(reftest__testdata=0)}}}

as sql:

{{{('SELECT U0.`id` FROM `test_generictest` U0 INNER JOIN `test_generictest` U1 ON (U0.`id` = U1.`id`) INNER JOIN `test_reftest` U2 ON (U1.`objectId` = U2.`id`) WHERE U2.`testdata` = %s ', (0,))}}}

With the applied patch, which made the same test, which is done in the direct case, the sql query looks like:

{{{('SELECT U0.`id` FROM `test_generictest` U0 INNER JOIN `test_reftest` U1 ON (U0.`id` = U1.`id`) WHERE U1.`testdata` = %s ', (0,))}}}

For simple databases and simple sql queries, this extra join is no problem, but with complex ones, its a huge performance lack."	Bug	closed	Database layer (models, ORM)	dev	Normal	needsinfo	database joins generic relation		Accepted	1	0	1	0	0	0
