Search code examples
pythondjangodjango-modelsdjango-orm

Django ORM ignore FilteredRelation condition


For some unknown reason condition in FilteredRelation seems to be ignored

annotations["passport_index"] = FilteredRelation("countrypassportindex", condition=Q(passport_index__year=2020))
queryset = self.settings.base_model.objects.annotate(**annotations).values(*values_orm_keys)

Here's queryset.query field value

SELECT
    "countries_countrytotaltradevalue"."value",
    "countries_countrytotaltradevalue"."year",
    "countries_countrymilitaryexpenses"."value",
    "countries_countrymilitaryexpenses"."year",
    "countries_countryeconomicfreedomindex"."value",
    "countries_countryeconomicfreedomindex"."year",
    "countries_countrypayingtaxesindex"."value",
    "countries_countrypayingtaxesindex"."year",
    "countries_countrysuiciderate"."value",
    "countries_countrysuiciderate"."year",
    "countries_countrypassportindex"."value",
    "countries_countrypassportindex"."year"
FROM "countries_country"
LEFT OUTER JOIN "countries_countrytotaltradevalue"
    ON ("countries_country"."id" = "countries_countrytotaltradevalue"."country_id")
LEFT OUTER JOIN "countries_countrymilitaryexpenses"
    ON ("countries_country"."id" = "countries_countrymilitaryexpenses"."country_id")
LEFT OUTER JOIN "countries_countryeconomicfreedomindex"
    ON ("countries_country"."id" = "countries_countryeconomicfreedomindex"."country_id")
LEFT OUTER JOIN "countries_countrypayingtaxesindex"
    ON ("countries_country"."id" = "countries_countrypayingtaxesindex"."country_id")
LEFT OUTER JOIN "countries_countrysuiciderate"
    ON ("countries_country"."id" = "countries_countrysuiciderate"."country_id")
LEFT OUTER JOIN "countries_countrypassportindex"
    ON ("countries_country"."id" = "countries_countrypassportindex"."country_id")

You can see that inside LEFT OUTER JOIN ... ON ("countries_country"."id" = "countries_countrypassportindex"."country_id") there is no "countries_countrypassportindex"."year" = 2019


Solution

  • String passport_index should be in values_orm_keys