Login

Choices class

Author:
dc
Posted:
November 10, 2008
Language:
Python
Version:
1.0
Tags:
models choices
Score:
7 (after 7 ratings)

Yet another class to simplify field choices creation. Keeps order, allows i18n.

Before:

ONLINE = 0
OFFLINE = 1
STATES = (
    (ONLINE, _('online')),
    (OFFLINE, _('offline'))
)

state = models.IntegerField(choices=STATES, default=OFFLINE)

After:

STATES = Choices(
    ('ONLINE', _('online')),
    ('OFFLINE', _('offline'))
)

state = models.IntegerField(choices=STATES, default=STATES.OFFLINE)
1
2
3
4
5
6
7
8
9
class Choices(object):
    def __init__(self, *args):
        self._choices = []
        for i, arg in enumerate(args):
            setattr(self, arg[0], i)
            self._choices.append((i, arg[1]))

    def __iter__(self):
        return iter(self._choices)

More like this

  1. Handling choices the right way by mallipeddi 7 years, 4 months ago
  2. Automatic Manager Choice Filters by nipuL 6 years, 2 months ago
  3. Online boolean switch in the admin list by sasha 7 years, 6 months ago
  4. ModelMixin by eallik 4 years, 4 months ago
  5. Retrieve human-readable value from choices tuple or value from dict by JoeLinux 2 years, 1 month ago

Comments

petar (on November 11, 2008):

This class if freaking awesome!

#

Please login first before commenting.