Login

Better Django Model Field Choices

Author:
jorjun
Posted:
March 2, 2011
Language:
Python
Version:
1.2
Score:
2 (after 2 ratings)

Nice to name your constant multiple choice fields in models, this is one way of doing that. Sorry I haven't looked into existing alternatives. But this approach worked for me.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from collections import namedtuple

from django.db.models import *


def _get_field_choices(named):
    """
    Namedtuple expected, return Django field choices
    """
    dictionary = named._asdict()
    return [(v, k) for (k, v) in dictionary.items()]

def get_named_choices(name, choices):
    choices = namedtuple(name, choices)(*range(len(choices)))
    return _get_field_choices(choices)


class Photo(Model):
    _image_types = {
        'COLOUR' : 0, 
        'BLACKWHITE' : 1, 
        'MONOCHROME' : 2, 
        'UNKNOWN' : 9, 
    }
    IMAGE_TYPE = get_named_choices('ImageType', _image_types)

    image_type = PositiveSmallIntegerField(
        default=0,
        choices=get_field_choices(IMAGE_TYPE)
    )

"""
usage: myphoto.image_type = Photo.IMAGE_TYPE.BLACKWHITE
"""

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

jorjun (on March 2, 2011):

CORRECTION (sorry)

def get_named_choices(name, choices): return namedtuple(name, choices)(*range(len(choices)))

#

jorjun (on March 2, 2011):

class Property: def init(self, kwd): for (key, val) in kwd.iteritems(): if isinstance(val, dict): val = Property(val) self.dict[key] = val

@property
def p_django_field_choices(self):
    return [(v, k) for (k, v) in self.__dict__.items()]

#

jorjun (on March 2, 2011):
class Property:
    def __init__(self, **kwd):
        for (key, val) in kwd.iteritems():
            if isinstance(val, dict):  val = Property(**val)
            self.__dict__[key] = val

    @property
    def p_django_field_choices(self):
        return [(v, k) for (k, v) in self.__dict__.items()]

#

Please login first before commenting.