Opened 5 years ago

Closed 5 years ago

#15950 closed New feature (duplicate)

Allow ChoiceField and friends to take a callable for choices kwarg

Reported by: jdunck Owned by: nobody
Component: Forms Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX:


Sometimes we'd like choices to be dynamic (often the result of an ORM query), but because models are declarative, this forces queries to run with Django partially loaded.

It would be good to be able to make choices a callable so that these queries could be deferred until Django is fully loaded.

I'm attaching a rough patch; if this passes design-decision, I can polish it up with tests.

Attachments (1)

callable-choice.diff (1.4 KB) - added by jdunck 5 years ago.

Download all attachments as: .zip

Change History (4)

Changed 5 years ago by jdunck

comment:1 Changed 5 years ago by jezdez

  • Component changed from Uncategorized to Forms
  • Triage Stage changed from Unreviewed to Accepted

Yeah, seems reasonable, although I'd prefer something like what the model fields do, taking any iterable instead:

Would that solve the issue for you, too?

comment:2 Changed 5 years ago by jdunck

Hmm, writing a generator to do a query only on the first execution of the generator is a little fiddly. (If there's a nice way to write it, please give an example.)

There's a common pattern of accepting callables - maybe we should add callable to model choices, too?

comment:3 Changed 5 years ago by julien

  • Resolution set to duplicate
  • Status changed from new to closed

This was actually already suggested in #13181.

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