code: def optgroups(self, name, value, attrs=None):
          
          default = (None, [], 0)
          groups = [default]
          has_selected = False
          selected_choices = {str(v) for v in value}
          if not self.is_required and not self.allow_multiple_selected:
              default[1].append(self.create_option(name, '', '', False, 0))
          if not isinstance(self.choices, ModelChoiceIterator):
              return super(ModelSelect2Mixin, self).optgroups(name, value, attrs=attrs)
          selected_choices = {
              c for c in selected_choices
              if c not in self.choices.field.empty_values
          }
          field_name = self.choices.field.to_field_name or 'pk'
          query = Q(**{'%s__in' % field_name: selected_choices})
          for obj in self.choices.queryset.filter(query):
              option_value = self.choices.choice(obj)[0]
              option_label = self.label_from_instance(obj)
  
              selected = (
                  str(option_value) in value and
                  (has_selected is False or self.allow_multiple_selected)
              )
              if selected is True and has_selected is False:
                  has_selected = True
              index = len(default[1])
              subgroup = default[1]
              subgroup.append(self.create_option(name, option_value, option_label, selected_choices, index))
          return groups
docs: Return only selected options and set QuerySet from `ModelChoicesIterator`.