ForeignKey filters use the wrong field to prepare values for database
|Reported by:||Russell Keith-Magee||Owned by:||Carl Meyer|
|Component:||Database layer (models, ORM)||Version:||1.0|
|Cc:||kmishler@…, Carsten Fuchs, Andrey Golovizin||Triage Stage:||Accepted|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||yes|
There are a couple of edge cases where filters on foreign keys can fail, as a result of a deep-seated problem with the way get_db_prep_value() is used.
If Model A has a foreign key pointing to B, a query of A.objects.filter(b=b_instance) will use the primary key on A to prepare the value for the database.
If both models have the same primary key type, this poses no problem.
- the two fields have a different get_db_prep_value() implementation (usually caused by having primary keys that are of substantially different types), or
- the foreign key specifies a to_field argument
then the value prepared for database lookup will be wrong.
Attached patch describes regression tests for this problem.