From 74afcee234f8be989623ccc7c28b9fb97fb548f0 Mon Sep 17 00:00:00 2001 From: Nick Pope Date: Mon, 16 Oct 2023 19:07:49 +0100 Subject: Refs #34899 -- Extracted Field.flatchoices to flatten_choices helper function. Co-authored-by: Natalia Bidart <124304+nessita@users.noreply.github.com> --- django/utils/choices.py | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'django/utils') diff --git a/django/utils/choices.py b/django/utils/choices.py index 734b9331a1..54dbdcb3aa 100644 --- a/django/utils/choices.py +++ b/django/utils/choices.py @@ -6,6 +6,7 @@ from django.utils.functional import Promise __all__ = [ "BaseChoiceIterator", "CallableChoiceIterator", + "flatten_choices", "normalize_choices", ] @@ -43,6 +44,15 @@ class CallableChoiceIterator(BaseChoiceIterator): yield from normalize_choices(self.func()) +def flatten_choices(choices): + """Flatten choices by removing nested values.""" + for value_or_group, label_or_nested in choices or (): + if isinstance(label_or_nested, (list, tuple)): + yield from label_or_nested + else: + yield value_or_group, label_or_nested + + def normalize_choices(value, *, depth=0): """Normalize choices values consistently for fields and widgets.""" # Avoid circular import when importing django.forms. -- cgit v1.3