Skip to content

Instantly share code, notes, and snippets.

@WTFox
Created May 14, 2018 23:11
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 WTFox/dde33e5e381c8ec438bf967ab6c6e26c to your computer and use it in GitHub Desktop.
Save WTFox/dde33e5e381c8ec438bf967ab6c6e26c to your computer and use it in GitHub Desktop.
class Car(models.Model):
COLOR_CHOICES = (
('RED', 'red'),
('WHITE', 'white'),
('BLUE', 'blue'),
)
color = models.CharField(max_length=5, choices=COLOR_CHOICES, default='RED')
# ...
red_cars = Car.objects.filter(color='RED')
class Car(models.Model):
RED = 'RED'
WHITE = 'WHITE'
BLUE = 'BLUE'
COLOR_CHOICES = (
(RED, 'red'),
(WHITE, 'white'),
(BLUE, 'blue'),
)
color = models.CharField(max_length=5, choices=COLOR_CHOICES, default=RED)
# ...
red_cars = Car.objects.filter(color=Car.RED)
from enum import Enum
class Color(Enum):
RED = 'red'
WHITE = 'white'
BLUE = 'blue'
# They're iterables
print([c for c in Color])
# >>> [Color.RED, Color.WHITE, Color.BLUE]
# Comparing..
Color.RED == Color.RED
# >>> True
# but comparisons against non-enumeration values will always be false.
# (See IntNum if that's something you're interested in.)
Color.RED == 'red'
# >>> False
# Values are accessed through .value.
Color.RED.value == 'red'
# >>> True
color = Color.RED
color.name
# >>> 'RED'
color.value
# >>> 'red'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment