QuerySet silently allows querying with objects of wrong class
|Reported by:||Chris Wilson||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.5-alpha-1|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
After a recent refactor, I thought our code was working correctly because the tests passed. Then I discovered that QuerySet allows you to pass objects of the wrong type in queries:
For example, this does not fail, and even returns some results:
Price.product is actually (now) a ForeignKey to
AccountType. The correct code would be this:
I think that QuerySet just extracts the object's PK without checking that it's an instance of the correct type.
I think it's not doing what is "obvious". I expect to get back
Price objects whose
product object is the same as the one I passed in, which is impossible if Price.product has a different class. Instead, it's silently rewritten my query into a less strict one, that only ensures that the FK is the same as the PK of the object I passed in, regardless of the type of that object.
Perhaps strictly it should return an empty set, because it's impossible for any Price objects to match the criteria that I provided, but I don't think that's very useful behaviour. Since this is a logic error in the application, I suggest throwing an exception to point it out instead.