Login

Django enumeration for model field choices

Author:
martinthenext
Posted:
March 28, 2012
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

The problem with supplying a Django model field with choices parameter is the way you check a value of that field in an object. You do nasty things like this:

if model_instance.choice_field == 1:

The problem of getting rid of hard-coded numbers is recognized over the internet, but I haven't found any short and understandable solution. Basically, we need a enumeration in python, that is ok to use as the Django choices model field argument.

I've seen a couple of solutions of DjangoSnippets. Mine is shorter and easier because it only works for integer field choices.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
"""
>>> states = Enum('OPEN', 'CLOSED')
>>> states.OPEN
0
>>> states.get_choices()
((0, 'OPEN'), (1, 'CLOSED'))
"""
class DjangoEnum(object):
    def __init__(self, *string_list):
        self.__dict__.update([(string, number) for (number, string)
                              in enumerate(string_list)])

    def get_choices(self):
        return tuple(enumerate(self.__dict__.keys())) 

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 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

Please login first before commenting.