I recently came across this article by Anthony Fox which shows how to use enums to create the choice set in django CharFields, which I thought was pretty neat.
Basically, you create a subclass of Enum:
from enum import Enum
class ChoiceEnum(Enum):
@classmethod
def choices(cls):
return tuple((x.name, x.value) for x in cls)
Which can then be used in your models like so:
from .utils import ChoiceEnum
class Car(models.Model):
class Colors(ChoiceEnum):
RED = 'red'
WHITE = 'white'
BLUE = 'blue'
color = models.CharField(max_length=5, choices=Colors.choices(), default=Colors.RED.value)
red_cars = Car.objects.filter(color=Car.Colors.RED.value)
However, pylint throws a warning whenever you try to access the enum value (Colors.RED.value)
E1101:Instance of 'str' has no 'value' member
Is there a way to avoid / disable this warning for every instance of ChoiceEnum?
This answer only works on the subclass of ChoiceEnum, not ChoiceEnum itself.
Since the issue is still open, we can use the following workaround
from .utils import ChoiceEnum
class Car(models.Model):
class Colors(ChoiceEnum, Enum):
RED = 'red'
WHITE = 'white'
BLUE = 'blue'
color = models.CharField(max_length=5, choices=Colors.choices(), default=Colors.RED.value)
This doesn't create the pylint error now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With