Florent
Florent

Reputation: 1928

How to access group name in Django choices?

I use nested tuples to organize and display choices in the admin section, and I would like to access the first element of the chosen tuple. In the example below, assuming the selected media is vinyl I would like get Audio. How can I do that ?

from django.db import models

class Student(models.Model):

    MEDIA_CHOICES = [
        ('Audio', (
                ('vinyl', 'Vinyl'),
                ('cd', 'CD'),
            )
        ),
        ('Video', (
                ('vhs', 'VHS Tape'),
                ('dvd', 'DVD'),
            )
        ),
        ('unknown', 'Unknown'),
    ]
    media = models.CharField(max_length=20, choices=MEDIA_CHOICES)

Upvotes: 3

Views: 89

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

As far as I know, there is no function for that, so you will need to write your own:

from django.db import models
from operator import itemgetter


class Student(models.Model):

    MEDIA_CHOICES = [
        (
            'Audio',
            (
                ('vinyl', 'Vinyl'),
                ('cd', 'CD'),
            ),
        ),
        (
            'Video',
            (
                ('vhs', 'VHS Tape'),
                ('dvd', 'DVD'),
            ),
        ),
        (
            None,
            (('unknown', 'Unknown'),)
        ),
    ]
    media = models.CharField(max_length=20, choices=MEDIA_CHOICES)

    @property
    def media_group(self):
        media = self.media
        return next(
            (
                g
                for g, vs in self.MEDIA_CHOICES
                if media in map(itemgetter(0), vs)
            ),
            None,
        )

This will return None in case the group can not be found, or if the group is None (see edits to the MEDIA_CHOICES.

Upvotes: 5

Related Questions