Skip to content

# `nautobot.apps.choices`

Utilities for implementing choices.

## `nautobot.apps.choices.ChoiceSet`

Base class for defining choices for a model and/or menu.

Subclasses should define a CHOICES constant which consists of a list of tuples of the form `(value, display_str)`, or optionally as tuples of the form `(grouping, ((value, display_str), (value, display_str), ...))`.

Example

    class GreekCapitalLetterChoices(ChoiceSet):
        ALPHA = "Α"
        BETA = "Β"
        GAMMA = "Γ"

        CHOICES = (
            (ALPHA, "alpha"),
            (BETA, "beta"),
            (GAMMA, "gamma"),
        )

Source code in `nautobot/utilities/choices.py`

    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    class ChoiceSet(metaclass=ChoiceSetMeta):
        """
        Base class for defining choices for a model and/or menu.

        Subclasses should define a CHOICES constant which consists of a list of tuples of the form `(value, display_str)`,
        or optionally as tuples of the form `(grouping, ((value, display_str), (value, display_str), ...))`.

        Example:
            ```python
            class GreekCapitalLetterChoices(ChoiceSet):
                ALPHA = "Α"
                BETA = "Β"
                GAMMA = "Γ"

                CHOICES = (
                    (ALPHA, "alpha"),
                    (BETA, "beta"),
                    (GAMMA, "gamma"),
                )
            ```
        """

        CHOICES = []

        @classmethod
        def values(cls):
            """Get a flat list of all values defined in this ChoiceSet's `CHOICES`."""
            return [c[0] for c in unpack_grouped_choices(cls.CHOICES)]

        @classmethod
        def as_dict(cls):
            """Get a dictionary representation of this ChoiceSet's `CHOICES`."""
            # Unpack grouped choices before casting as a dict
            return dict(unpack_grouped_choices(cls.CHOICES))

### `as_dict()` `classmethod`

Get a dictionary representation of this ChoiceSet's `CHOICES`.

Source code in `nautobot/utilities/choices.py`

    44
    45
    46
    47
    48
    @classmethod
    def as_dict(cls):
        """Get a dictionary representation of this ChoiceSet's `CHOICES`."""
        # Unpack grouped choices before casting as a dict
        return dict(unpack_grouped_choices(cls.CHOICES))

### `values()` `classmethod`

Get a flat list of all values defined in this ChoiceSet's `CHOICES`.

Source code in `nautobot/utilities/choices.py`

    39
    40
    41
    42
    @classmethod
    def values(cls):
        """Get a flat list of all values defined in this ChoiceSet's `CHOICES`."""
        return [c[0] for c in unpack_grouped_choices(cls.CHOICES)]