Hi!
On Thu, Jun 9, 2011 at 8:06 PM, cool-RR <[email protected]> wrote:
> Anyway I'll try to start using `flufl.enum` soon. One awesome application
> that this could have is to make a Django `EnumField` (or `ChoiceField` or
> whatever you want to call it) instead of the current ugly way of making an
> `IntegerField` and defining `CHOICES` separately.
>
My not-so-perfect KISS/DRY/Just-works solution (for example, without i18n
support) for having many enum-like/"choices" classes in Django is:
def break_and_capitalize(s):
return " ".join([word.capitalize() for word in s.split("_")])
def choices_from_class(cls):
return [(cls.__dict__[key] , break_and_capitalize(key)) for key in
cls.__dict__ if 'A'<=key[0]<='Z']
...
class Fruit(object):
APPLE = 1
BANANA = 2
PEAR = 3
ORANGE= 4
...
class Whatever(models.Model):
fruit = models.IntegerField(choices=*choices_from_class*(Fruit),
default=Fruit.APPLE)
I guess you can create a simple EnumField from this, lifting the DRY level
by one less function call.
Udi
_______________________________________________
Python-il mailing list
[email protected]
http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il