Opened 7 years ago

Closed 6 years ago

Last modified 4 years ago

#9643 closed (invalid)

Custom managers on related objects generating incorrect SQL

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

Description

Using these models, we can generate incorrect SQL.

class Report(models.Model):
    name = models.CharField(max_length=100)

class TaskManager(models.Manager):
    def get_milestones(self):
        return super(TaskManager, self).get_query_set().filter(milestone=True)

class Task(models.Model):
    report = models.ForeignKey(Report)
    name = models.CharField(max_length=100)
    milestone = models.BooleanField(default=False)

    objects = TaskManager()

    def __unicode__(self):
        return u"%s" % self.name

This gives the correct result:

>>> r = Report.objects.get(name="r1")
>>> r.task_set.filter(milestone=True)

This does not (it doesn't filter on report_id):

>>> r.task_set.get_milestones()

Whoopsie. :-(

Change History (3)

comment:1 Changed 6 years ago by jacob

  • milestone set to 1.1
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

comment:2 Changed 6 years ago by mtredinnick

  • Resolution set to invalid
  • Status changed from new to closed

I'm an idiot. The bug is in the example code: get_milestones() should be calling self.get_query_set(), not super's get_query_set(). This works fine

def get_milestones(self):
   return self.get_query_set().filter(milestone=True)

PEBKAC. :-(

comment:3 Changed 4 years ago by jacob

  • milestone 1.1 deleted

Milestone 1.1 deleted

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