another problem with M2M through intermediary

3 views
Skip to first unread message

akonsu

unread,
Aug 20, 2008, 12:30:29 AM8/20/08
to Django users
hello,

consider the code below. it has two print statements at the end. their
output should be identical, but it is not. i think there is a bug.

thanks
konstantin

class X(models.Model) :
name = models.SlugField()
def __str__(self) : return self.name

class Y(models.Model) :
name = models.SlugField()
xs = models.ManyToManyField(X, through = 'Pair')
def __str__(self) : return self.name

class Pair(models.Model) :
name = models.SlugField()
x = models.ForeignKey(X)
y = models.ForeignKey(Y)
def __str__(self) : return "(%s,'%s',%s)" % (self.x, self.name,
self.y)
...
x0, _ = X.objects.get_or_create(name = 'x0')
x1, _ = X.objects.get_or_create(name = 'x1')

y0, _ = Y.objects.get_or_create(name = 'y0')
y1, _ = Y.objects.get_or_create(name = 'y1')

p0, _ = Pair.objects.get_or_create(name = 'a', y = y0, defaults =
{ 'x' : x0 })
p1, _ = Pair.objects.get_or_create(name = 'b', y = y0, defaults =
{ 'x' : x1 })
p2, _ = Pair.objects.get_or_create(name = 'c', y = y1, defaults =
{ 'x' : x0 })
p3, _ = Pair.objects.get_or_create(name = 'd', y = y1, defaults =
{ 'x' : x1 })

print [p.x for p in Pair.objects.filter(y = y0, name = 'd')]
print y0.xs.filter(pair__name = 'd')

...

output:
[]
[<X: x1>]

Russell Keith-Magee

unread,
Aug 20, 2008, 8:01:44 AM8/20/08
to django...@googlegroups.com
On Wed, Aug 20, 2008 at 12:30 PM, akonsu <ako...@gmail.com> wrote:
>
>
> consider the code below. it has two print statements at the end. their
> output should be identical, but it is not. i think there is a bug.
...

> print [p.x for p in Pair.objects.filter(y = y0, name = 'd')]
> print y0.xs.filter(pair__name = 'd')

I'm pretty certain this is another manifestation of #8046. Looking at
the SQL generated, the second case is doing a redundant join, which is
resulting in the stray result. I've added a note on that ticket -
thanks for the helpful test case.

Yours,
Russ Magee %-)

Reply all
Reply to author
Forward
0 new messages