Skip to content

Instantly share code, notes, and snippets.

@teror4uks
Created December 25, 2017 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teror4uks/78bd6547ff55d8fe52bf35734ed0b299 to your computer and use it in GitHub Desktop.
Save teror4uks/78bd6547ff55d8fe52bf35734ed0b299 to your computer and use it in GitHub Desktop.
namedtuple_choices.py
def get_namedtuple_choices(name, choices_tuple):
"""Factory function for quickly making a namedtuple suitable for use in a
Django model as a choices attribute on a field. It will preserve order.
Usage::
class MyModel(models.Model):
COLORS = get_namedtuple_choices('COLORS', (
(0, 'BLACK', 'Black'),
(1, 'WHITE', 'White'),
))
colors = models.PositiveIntegerField(choices=COLORS.get_choices())
> MyModel.COLORS.BLACK
0
> MyModel.COLORS.get_choices()
[(0, 'Black'), (1, 'White')]
class OtherModel(models.Model):
GRADES = get_namedtuple_choices('GRADES', (
('FR', 'FR', 'Freshman'),
('SR', 'SR', 'Senior'),
))
grade = models.CharField(max_length=2, choices=GRADES.get_choices())
> OtherModel.GRADES.FR
'FR'
> OtherModel.GRADES.get_choices()
[('FR', 'Freshman'), ('SR', 'Senior')]
"""
class Choices(collections.namedtuple(name, [name for val, name, desc in choices_tuple])):
__slots__ = ()
_choices = tuple([desc for val, name, desc in choices_tuple])
def get_choices(self):
return zip(tuple(self), self._choices)
return Choices._make([val for val, name, desc in choices_tuple])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment