Choices datatype for model

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class django_choices(tuple):
    '''
    Creates a choices data type like what django needs for models. 
    '''
    def __new__(self, *args, **kwargs):
        self.choices = []
        if kwargs:
          for val in kwargs.values():
              for key in kwargs.keys():
                if kwargs[key] == val:
                  self.choices.append((val, key))
        return tuple.__new__(self, self.choices or args)
        
    def to_dict(self):
        '''
        Automatically converts the choices to a dictionary. Useful for type lookups.
        '''
        d = {}
        for choice in self:
            d[choice[1].lower()] = choice[0]
        return d

More like this

  1. Model Choices Helper by pmclanahan 3 years, 3 months ago
  2. Choices by cronosa 3 years, 4 months ago
  3. More readable Enumeration class for Django choices by achimnol 3 years, 10 months ago
  4. Handling choices the right way by mallipeddi 5 years, 6 months ago
  5. The model field subclass returns string generated from the list of choices. by I159 1 year, 6 months ago

Comments

menendez (on May 20, 2008):

The old syntax is also supported if you just want the methods:

django_choices( (0,'Manual'), (1,'Automatic'), )

#

(Forgotten your password?)