Django: optiongroups for your ModelChoice Field

With a normal Django ChoiceField you can specify choices either as a simple tuple of tuples (value, label pairs) or with an extra level structure to organise the choices into named groups. The Django Select widget will then happily render the choices into html optiongroups.

With a ModelChoiceField you don’t specify the choices directly, you give a queryset of results from the db, which just has a flat structure.

I’ve made a ‘GroupedModelChoiceField’ that allows to output optiongroups based on a field from the model in your queryset. Code is here on djangosnippets… simple as that!


Django: chaining custom model Manager methods

As Simon Willison points out:

“Django supports adding custom methods for accessing the ORM through the ability to implement a custom Manager… The downside of this approach is that methods added to a manager can only be used at the beginning of the chain.”

My modest contribution is in this comment on DjangoSnippets…