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