From f2ef1b00ce543c560446297ecea3b39411619965 Mon Sep 17 00:00:00 2001 From: David Underhill Date: Sat, 3 Apr 2010 10:40:19 -0400 Subject: [PATCH] set uppercase versions of any string choices as attributes on the ChoiceProperty => easier to get choice->index mapping than c2i() -- Thanks to Nick Johnson for this suggestion too :) --- __init__.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/__init__.py b/__init__.py index 616f00b..a122be2 100644 --- a/__init__.py +++ b/__init__.py @@ -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."""