Opened 10 years ago

Closed 10 years ago

#24002 closed Bug (fixed)

.filter(generic_rel=val) should filter on related model primary key value, not the object_id value

Reported by: Anssi Kääriäinen Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Doing Publisher.objects.filter(book=1) currently produces a query with WHERE book.object_id = 1 (assuming book is GenericRelation field). That is, the filter targets object_id field of book. Filtering on reverse side of a foreign key relation does however target the primary key field of the related model. Similarly aggregating over generic relation targets the object_id field, not the primary key field.

The most problematic case is doing a query like Publisher.objects.filter(book=somebook.pk). This doesn't work correctly with generic relations, but works nicely with reverse foreign key relations.

Unfortunately fixing this changes behavior of currently working code, and I can't think of any sensible way to do this with backwards compatibility period. So, I suggest we just treat this as a bug fix for master.

Change History (1)

comment:1 by Anssi Kääriäinen <akaariai@…>, 10 years ago

Resolution: fixed
Status: newclosed

In 1c5cbf5e5d5b350f4df4aca6431d46c767d3785a:

Fixed #24002 -- GenericRelation filtering targets related model's pk

Previously Publisher.objects.filter(book=val) would target
book.object_id if book is a GenericRelation. This is inconsistent to
filtering over reverse foreign key relations, where the target is the
related model's primary key.

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