Skip to content

Commit

Permalink
set uppercase versions of any string choices as attributes on the Cho…
Browse files Browse the repository at this point in the history
…iceProperty => easier to get choice->index mapping than c2i()

  -- Thanks to Nick Johnson for this suggestion too :)
  • Loading branch information
dound committed Apr 3, 2010
1 parent 070dc2d commit f2ef1b0
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion __init__.py
Expand Up @@ -530,16 +530,22 @@ class ChoiceProperty(db.IntegerProperty):
>>> ChoiceModel.gql("WHERE a_choice = :1", green).count()
1
"""
def __init__(self, choices, *args, **kwargs):
def __init__(self, choices, make_choice_attrs=True, *args, **kwargs):
"""Constructor.
Args:
choices: A non-empty list of 2-tuples of the form (id, choice). id must be
the int to store in the database. choice may be any hashable value.
make_choice_attrs: If True, the uppercase version of each string choice is
set as an attribute whose value is the choice's int representation.
"""
super(ChoiceProperty, self).__init__(*args, **kwargs)
self.index_to_choice = dict(choices)
self.choice_to_index = dict((c,i) for i,c in self.index_to_choice.iteritems())
if make_choice_attrs:
for i,c in self.index_to_choice.iteritems():
if isinstance(c, basestring):
setattr(self, c.upper(), i)

def get_choices(self):
"""Gets a list of values which may be assigned to this property."""
Expand Down

0 comments on commit f2ef1b0

Please sign in to comment.