How to add optgroup tag to ManyToMany select field?

I have these models:

class Classification(models.Model):
    **group**= models.CharField()
    category = models.CharField()
    statement = models.CharField()

    def __str__(self):
        return '%s - %s' % (self.category, self.statement)

class Ghs(models.Model):
    name = models.CharField()
    classification = models.ManyToManyField(
        Classification,
    )

How can I add optgroup tag (based on group field) to the select field in form?

The general form for using optgroup in a select field requires the choices look like this:

(
  ('OptGroup 1', [('value 1', 'display 1'), ('value 2', 'display 2')],
  ('OptGroup 2', ...
 )

I don’t know how practical it would be to create a queryset to return results like this. (I’d be mostly concerned about the ability for the validators to function with an unexpected queryset structure.)

It may be necessary to create a custom field that would take the queryset and transform it into the nested iterables needed for the existing templates to work - while allowing the validation functions to also work.

Alternatively, you might be able to define a custom widget that accepts a more typical queryset but iterates over the groups, using the ifchanged tag to identify when to insert the optgroup tag in the options.

Thank you. I’ll try a custom widget.