Login

Choices datatype for model

Author:
menendez
Posted:
March 26, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 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'), )

#

Please login first before commenting.