Skip to content

Instantly share code, notes, and snippets.

@cdosborn
Last active November 4, 2016 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdosborn/cb4bdfd0467feaf987476f4aefdf7ee5 to your computer and use it in GitHub Desktop.
Save cdosborn/cb4bdfd0467feaf987476f4aefdf7ee5 to your computer and use it in GitHub Desktop.
Code sample that demonstrates issues with chained filtering
> from core.models import Application
> from django.db.models import Q
> test = Q(tags__name__startswith='a')
> # Below are two queries that are appear to be the same but are /very/ different
> print Application.objects.filter(test).filter(test).filter(test).query
SELECT *
FROM "application"
INNER JOIN "application_tags" ON ( "application"."id" = " application_tags"."application_id")
INNER JOIN "tag" ON ("application_tags"."tag_id" = "tag"."id")
INNER JOIN "application_tags" T4 ON ("application"."id" = T4."application_id")
INNER JOIN "tag" T5 ON (T4."tag_id" = T5."id")
INNER JOIN "application_tags" T6 ON ("application"."id" = T6."application_id")
INNER JOIN "tag" T7 ON (T6."tag_id" = T7."id")
WHERE (
"tag"."name"::TEXT LIKE a %
AND T5."name"::TEXT LIKE a %
AND T7."name"::TEXT LIKE a %
)
> print Application.objects.filter(test & test & test).query
SELECT *
FROM "application"
INNER JOIN "application_tags" ON ( "application"."id" = " application_tags"."application_id")
INNER JOIN "tag" ON ("application_tags"."tag_id" = "tag"."id")
WHERE (
"tag"."name"::TEXT LIKE a %
AND "tag"."name"::TEXT LIKE a %
AND "tag"."name"::TEXT LIKE a %
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment