#18432: Chained foreign keys with to_field produce incorrect query
----------------------------------------------+--------------------
Reporter: lwarx | Owner: nobody
Type: Bug | Status: new
Component: Database layer (models, ORM) | Version: 1.3
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 0
Easy pickings: 0 | UI/UX: 0
----------------------------------------------+--------------------
Example models:
{{{
class Model1(models.Model):
pkey = models.IntegerField(unique=True, db_index=True)
class Model2(models.Model):
model1 = models.ForeignKey(Model1, unique=True, to_field='pkey')
class Model3(models.Model):
model2 = models.ForeignKey(Model2, unique=True, to_field='model1')
}}}
Steps to reproduce:
{{{
m1 = Model1(pkey=1000); m1.save(); m2 = Model2(model1=m1); m2.save(); m3 =
Model3(model2=m2); m3.save()
(0.000) INSERT INTO `testcase_model1` (`pkey`) VALUES (1000); args=(1000,)
(0.000) INSERT INTO `testcase_model2` (`model1_id`) VALUES (1000);
args=(1000,)
(0.000) INSERT INTO `testcase_model3` (`model2_id`) VALUES (1000);
args=(1000,)
m3 = Model3.objects.get(model2=1000)
(0.001) SELECT `testcase_model3`.`id`, `testcase_model3`.`model2_id` FROM
`testcase_model3` WHERE `testcase_model3`.`model2_id` = 1000 ;
args=(1000,)
m3.model2
(0.000) SELECT `testcase_model2`.`id`, `testcase_model2`.`model1_id` FROM
`testcase_model2` INNER JOIN `testcase_model1` ON
(`testcase_model2`.`model1_id` = `testcase_model1`.`pkey`) WHERE
`testcase_model1`.`id` = 1000 ; args=(1000,)
}}}
In the last query WHERE condition is incorrect - it does not respect
to_field attribute and uses primary key instead.
Error message:
{{{
DoesNotExist Traceback (most recent call
last)
/private/tmp/fkchain/<ipython-input-5-2fce98c5af10> in <module>()
----> 1 m3.model2
/Library/Python/2.7/site-packages/django/db/models/fields/related.pyc in
__get__(self, instance, instance_type)
313 rel_obj = rel_mgr.using(db).get(**params)
314 else:
--> 315 rel_obj =
QuerySet(self.field.rel.to).using(db).get(**params)
316 setattr(instance, cache_name, rel_obj)
317 return rel_obj
/Library/Python/2.7/site-packages/django/db/models/query.pyc in get(self,
*args, **kwargs)
347 if not num:
348 raise self.model.DoesNotExist("%s matching query does
not exist."
--> 349 % self.model._meta.object_name)
350 raise self.model.MultipleObjectsReturned("get() returned
more than one %s -- it returned %s! Lookup parameters were %s"
351 % (self.model._meta.object_name, num, kwargs))
DoesNotExist: Model2 matching query does not exist.
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/18432>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-updates?hl=en.