Opened 5 years ago

Closed 5 years ago

#21434 closed Bug (fixed)

IN clause not supporting the to_field

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


I think this is similar to bug 17972.

If I have a model defined:

   class VolumeTemplate(models.Model):
       parent = models.ForeignKey(
          'Volume', null=True, blank=True, to_field='uuid', related_name='parent_templates')

   class BracketVolume(models.Model):
       uuid = UUIDField(version=4, auto=True, db_index=True, unique=True)

The following query returns an empty result set, even if the parent is non None:

   queryset = Volume.objects.all()

However the following will return the corresponding VolumeTemplates:


This is because the subquery generated by the IN clause does not take the to_field into consideration and instead returns a list of values instead of Volume.uuid values. The SQL is comparing the parent_id which is a UUID field due to the to_field.

Change History (1)

comment:1 Changed 5 years ago by Baptiste Mispelon

Cc: Baptiste Mispelon added
Component: UncategorizedDatabase layer (models, ORM)
Resolution: fixed
Status: newclosed


I can indeed reproduce the issue on the 1.5 branch, using the two following models:

from django.db import models

class Foo(models.Model):
    foo = models.CharField(max_length=1, db_index=True, unique=True)

class Bar(models.Model):
    foo = models.ForeignKey(Foo, to_field='foo')

With these models, the following code shows the issue: assert Bar.objects.filter(foo__in=Foo.objects.all()).count() (this requires having created one model of each kind in the database).

Having this code, I was able to track down the commit that fixed this issue in the master branch (also present in 1.6, as it turns out): 97774429aeb54df4c09895c07cd1b09e70201f7d.

Seeing as this issue is not a regression (and therefore its fix is unlikely to get backported), I'm going to mark this ticket as fixed.
Feel free to reopen the ticket if you think otherwise of course.

Thanks for your report.

Note: See TracTickets for help on using tickets.
Back to Top