﻿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
32239	FilteredRelation is not working with GenericRelation	Omar Altayyan	nobody	"I have the following models:
{{{
class Workspace(Model):
    pass

class Event(Model):
    workspace = ForeignKey(Workspace)

    limit = FloatField(default=0)

    entity_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    entity_id = models.PositiveIntegerField()
    entity = GenericForeignKey('entity_type', 'entity_id')

class Entity(Model):
    events = GenericRelation(Event, content_type_field='entity_type', object_id_field='entity_id')

    class Meta:
        abstract = True

class SomeEntity(Entity):
    pass
}}}
Now I need to build a queryset to sort objects of SomeEntity by the limit of their events inside a given Workspace

The SQL query I'm hoping to have is something like this:
{{{
SELECT 
    ""some_entity"".""id"", workspace_events.""id"", COALESCE(workspace_events.""limit"", 0) AS ""limit"" 
FROM ""some_entity"" LEFT OUTER JOIN ""event"" workspace_events
    ON (
        ""some_entity"".""id"" = workspace_events.""entity_id"" AND 
        workspace_events.""entity_type_id"" = SOME_ENTITY_CONENT_TYPE_ID AND
        workspace_events.""workspace_id"" = GIVEN_WORKSPACE_ID
    )
) ORDER BY ""limit"" DESC'
}}}
Where:

SOME_ENTITY_CONTENT_TYPE_ID is the content type id of the SomeEntity model.
GIVEN_WORKSPACE_ID is the workspace id I want to filter the events on.
The queryset I'm using is this:
{{{
SomeEntity.objects.annotate(
    workspace_events=FilteredRelation('events', condition=Q(events__workspace_id=GIVEN_WORKSPACE_ID)),
    limit=Coalesce('workspace_events__limit', 0),
).values('id', 'workspace_events__id', 'limit').order_by('-limit')
}}}
But the query I'm getting from the above queryset doesn't include the workspace condition in the join at all!


{{{
SELECT 
    ""some_entity"".""id"", workspace_events.""id"", COALESCE(workspace_events.""limit"", 0) AS ""limit"" 
FROM ""some_entity"" LEFT OUTER JOIN ""event"" workspace_events
    ON (
        ""some_entity"".""id"" = workspace_events.""entity_id"" AND 
        workspace_events.""entity_type_id"" = SOME_ENTITY_CONENT_TYPE_ID AND
    )
) ORDER BY ""limit"" DESC'

}}}

it seems that workspace condition is not being added to the join conditions, so it probably needs a fix.

"	Bug	closed	Database layer (models, ORM)	3.1	Normal	needsinfo	FilteredRelation GenericRelation Generic Relation		Unreviewed	0	0	0	0	0	0
