Opened 10 years ago

Closed 10 years ago

Last modified 10 years ago

#23354 closed Bug (fixed)

ModelChoiceField does not handle MultipleObjectsReturned

Reported by: Keryn Knight Owned by: nobody
Component: Forms Version: dev
Severity: Normal 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

As far as I can gather [that is, this hasn't actually bitten me], the to_python for ModelChoiceField does not catch the queryset model's MultipleObjectsReturned exception, which in most cases will be fine because the query will be against the pk, which is ostensibly unique unless a user has gone out of their way to break things.

However, given the ability to use to_field_name (which was recently documented [in #21860], increasing the likelihood of it's usage) it is feasible that a user would end up using a field which is not unique (or even spans a relationship?), and thus in a simple key:value lookup could return multiple rows.

This would also technically affect the ModelMultipleChoiceField, whose superclass is ModelChoiceField and whose to_python method is used for each value.

Change History (3)

comment:1 by Tim Graham, 10 years ago

Shouldn't we just document that to_field_name must be able to uniquely identify the objects? I'm not sure what error message we'd present since it's presumably a programming error and not something a user could fix.

comment:2 by Tim Graham <timograham@…>, 10 years ago

Resolution: fixed
Status: newclosed

In 83762da3fbc00fdb5c6cfbcd04e25ff00c599102:

Fixed #23354 -- Documented that ModelChoiceField to_field_name should be a unique field.

Thanks Keryn Knight for the suggestion.

comment:3 by Tim Graham <timograham@…>, 10 years ago

In e86030b3be2ac9af4a2855d88802c0b750152c8a:

[1.7.x] Fixed #23354 -- Documented that ModelChoiceField to_field_name should be a unique field.

Thanks Keryn Knight for the suggestion.

Backport of 83762da3fb from master

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