#12615 closed (invalid)
Broken queryset indexing with postgresql_psycopg2 with custom through model
Reported by: | yxven | Owned by: | nobody |
---|---|---|---|
Component: | Uncategorized | Version: | 1.1-beta |
Severity: | Keywords: | ||
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
If you start a new project and setup a database using postgresl_psycopg2 (I know sqlite3 works. I dunno about others), and create a model that uses a custom through model, queryset indexing will be broken when accessed through that relationship.
I've attached a simplified models.py and tests.py to explain and demonstrate it.
Attachments (2)
Change History (4)
by , 15 years ago
by , 15 years ago
comment:1 by , 15 years ago
Resolution: | → invalid |
---|---|
Status: | new → closed |
Note:
See TracTickets
for help on using tickets.
Although confusing, this actually isn't an error on Django's part. Your code is making an assumption that isn't valid.
Your failing test case is essentially the following code:
You are assuming that zipcodes is an ordered list, and that you are indexing into that list. You aren't. Zipcodes is an unevaluated queryset. The queryset is evaluated twice - once for each subscript.
zipcodes[0]
translates to the SQL query:... and
zipcodes[1]
translates to:Zipcodes doesn't have any inherent ordering, so there is no guarantee that the database will return zipcode objects in the same order for the two queries. As a result, you are seeing id=2 returned for both queries.
This won't even be 100% reproducible - it really does depend on the internals of the database at the time you run the two queries. The inconsistency between databases is one example of how this problem can manifest.
There are several ways you can fix your code: