Login

Choices datatype for model

Author:
menendez
Posted:
March 26, 2008
Language:
Python
Version:
.96
Tags:
choices model
Score:
1 (after 1 ratings)

This class will automatically create a django choices tuple like this:

STATUS_CHOICES = django_choices(Draft=1, Public=2, Closed=3)

Additionally, it includes a method that converts the choices tuple to a dictionary. Like this:

STATUS = STATUS_CHOICES.to_dict()

Those types can come in handy when you need to use those magic values in your code. Best done within the model once so everyone can use it. Code based on: http://www.djangosnippets.org/snippets/455/.

By the way, if you want to just have the method without having to convert to the newer syntax.. it's backward compatible. Just add django_choices in front of the first paren for your choices tuple.

 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. Enumeration field by nail.xx 6 years, 8 months ago
  2. Subdirectory and subcontext include template tag with examples by t_rybik 5 years ago
  3. Getting dynamic model choices in newforms by ubernostrum 8 years, 1 month ago
  4. Forms splitted in fieldsets by gustavo80br 7 years ago
  5. Rendering radio-buttons with icons instead of labels by jeverling 5 years 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'), )

#

Please login first before commenting.