Opened 7 years ago

Closed 7 years ago

#28551 closed Bug (duplicate)

Exclude query on M2M field with F() fails

Reported by: daishi Owned by: nobody
Component: Database layer (models, ORM) Version: 1.11
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Tim Graham)

Given the following models:

class A(models.Model):

class B(models.Model):
    a = models.ManyToManyField(A)

class C(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)

The following test:

a1 = A()
a2 = A()
b1 = B()
b2 = B()
c1 = C(a=a1, b=b1)
c2 = C(a=a1, b=b2)
self.assertEqual(1, C.objects.filter(b__a=F('a')).count())
self.assertEqual(1, C.objects.exclude(b__a=F('a')).count())

Fails with the following error:

OperationalError: no such column:

The SQL generated by Django for the C.objects.exclude(b__a=F('a')) fragment is logged as:

SELECT "a_c"."id", "a_c"."a_id", "a_c"."b_id" FROM "a_c" WHERE NOT ("a_c"."b_id" IN (SELECT U3."b_id" AS Col1 FROM "a_c" U0 INNER JOIN "a_b_a" U3 ON (U2."id" = U3."b_id") WHERE U3."a_id" = (U0."a_id"))) LIMIT 21; args=()

As suggested in the error, the U2 join table does not seem to be defined in the generated query.

Change History (2)

comment:1 by Tim Graham, 7 years ago

Component: UncategorizedDatabase layer (models, ORM)
Description: modified (diff)
Type: UncategorizedBug

Looks like a duplicate of #21703.

comment:2 by Tim Graham, 7 years ago

Resolution: duplicate
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top