Search code examples
pythondjangoflattenoptgroup

flatten python tuple - django field options optgroups


I've been looking for a way to flatten a field's options in django that is structured as optgroup nested tuples:

CHOICES = (
  ('', (
        ('value1', 'label1'),
        ('value2', 'label2'),
      )
  ),
  ('Group2', (
        ('value3', 'label3'),
        ('value4', 'label4'),
     )
  ),
)

What I want to achieve is a list containing only the values ['value1', 'value2', 'value3', 'value4'].

I have tried itertools chain, zip and sum but I cannot get rid of the grouping labels, that is the empty string '' and 'Group2'. Any ideas?

Thank you


Solution

  • For anyone interested, the following will do:

    [tuple[0] for tuple in [field].get_flatchoices(False)]