Choice Fields (Or Enum equivalent) refactors
See original GitHub issueI am working on Issue #291 . I cant help but notice the code snippets like if conference.status != 1:
from junction/proposals/views.py (It might be in some other places too). It is not immediately apparent what 1
represents. I have to open junction/base/constants.py to cross-reference with the file and understand what it is.
So I am raising an Issue here to propose a refactor. To deal with choices
field I wrote a handy decorator. It goes something like this:
import inspect
def user_attributes(cls):
defaults = dir(type('defaults', (object,), {})) # gives all inbuilt attrs
return [
item[0] for item in inspect.getmembers(cls) if item[0] not in defaults]
def choices(cls):
"""
Decorator to set `CHOICES` attribute
"""
_choices = []
for attr in user_attributes(cls):
val = getattr(cls, attr)
_choices.append((val, attr))
setattr(cls, 'CHOICES', tuple(_choices))
return cls
@choices
class FooEnum:
FOO = 1
BAR = 2
print FooEnum.CHOICES # Will contain `((2, 'BAR'), (1, 'FOO'))`
I also understand we might need some custom get_<choice_field>_display
messages. For that I think we can tweak the choices decorator to do the same. That will be something like this.
import inspect
def user_attributes(cls):
defaults = dir(type('defaults', (object,), {})) # gives all inbuilt attrs
return [
item[0] for item in inspect.getmembers(cls) if item[0] not in defaults]
def choices(cls):
"""
Decorator to set `CHOICES` and other attributes
"""
_choices = []
for attr in user_attributes(cls):
val = getattr(cls, attr)
setattr(cls, attr[1:], val[0])
_choices.append((val[0], val[1]))
setattr(cls, 'CHOICES', tuple(_choices))
return cls
@choices
class FooEnum:
_FOO = [1, "Some Foo String"]
_BAR = [2, "Some Bar String"]
print FooEnum.CHOICES # ((2, 'Some Bar String'), (1, 'Some Foo String'))
print FooEnum.FOO # 1
So we could do something like if conference.status != ConferenceStatus.ACCEPTING_CFP:
which makes code base A bit readable and pragmatic.
Any thoughts @kracekumar ?
Issue Analytics
- State:
- Created 8 years ago
- Comments:5 (4 by maintainers)
Top GitHub Comments
@dhilipsiva Sure, but one feature which will be useful is reverse lookup. If choice
Public
is1
, db contains1
, while returning the data via api, field need to bare the value asPublic
not 1.@kracekumar I created a stand alone decorator for doing this dhilipsiva/orm-choices. Would it be okay if I refactored this code to use the
orm-choices
library and send a PR?