Tuesday, September 6, 2011

multiple filters on the same (reversed) foreignkey leads to multiple join

A clean project/app in django 1.3 with just two models

from django.db import models

class Base(models.Model):
pass

class Child(models.Model):
base = models.ForeignKey(Base)
flag1 = models.BooleanField()
flag2 = models.BooleanField()

A Queryset with a single use of `.filter` works as expected:
>>> qs = Base.objects.filter(child__flag1=True)
>>> print qs.query
SELECT "t0_base"."id"
FROM "t0_base" INNER JOIN "t0_child"
ON ("t0_base"."id" = "t0_child"."base_id")
WHERE "t0_child"."flag1" = True

but if I start to add additional filters...
>>> qs = qs.filter(child__flag2=True)
>>> print qs.query
SELECT "t0_base"."id"
FROM "t0_base" INNER JOIN "t0_child"
ON ("t0_base"."id" = "t0_child"."base_id")
INNER JOIN "t0_child" T3
ON ("t0_base"."id" = T3."base_id")
WHERE ("t0_child"."flag1" = True AND T3."flag2" = True )

>>> qs = qs.filter(child__flag1=False)
>>> print qs.query
SELECT "t0_base"."id"
FROM "t0_base" INNER JOIN "t0_child"
ON ("t0_base"."id" = "t0_child"."base_id")
INNER JOIN "t0_child" T3
ON ("t0_base"."id" = T3."base_id")
INNER JOIN "t0_child" T4
ON ("t0_base"."id" = T4."base_id")
WHERE ("t0_child"."flag1" = True AND T3."flag2" = True AND
T4."flag1" = False )

I don't think that this is the expected behavior, should I open a new
bug?

david

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate