在这种特殊情况下,我会将十六进制颜色代码存储在模型中的字段中。
在本质上:
class Event(models.Model):
ALERT = "alert"
WARNING = "warning"
ERROR = "error"
EVENT_TYPES = (
(ALERT, "Alert"),
(WARNING, "Warning"),
(ERROR, "Error"),
)
YELLOW = "FF6A00"
ORANGE = "FFE800"
RED = "FF0000"
COLOURS = (
(YELLOW, "Yellow"),
(ORANGE, "Orange"),
(RED, "Red"),
)
event_type = models.CharField(max_length=16, choices=EVENT_TYPES, default=ALERT)
event_colour = models.CharField(max_length=6, choices=COLOURS, default=YELLOW)
附加说明,“常量”的原因是为了使使用此模型的代码简洁明了。
# example 1
error_events = Event.objects.filter(event_type=Event.ERROR)
# example 2
if my_event.event_type == Event.Error:
# this is an error event
pass
此外,这是一种在模型上没有颜色字段的情况下可以做到的方法:
class Event(models.Model):
ALERT = "alert"
WARNING = "warning"
ERROR = "error"
EVENT_TYPES = (
(ALERT, "Alert"),
(WARNING, "Warning"),
(ERROR, "Error"),
)
# map events to colours
COLOUR = {
ALERT: "FF6A00",
WARNING: "FFE800",
ERROR: "FF0000",
}
event_type = models.CharField(max_length=16, choices=EVENT_TYPES, default=ALERT)
@property
def colour(self):
"""
Return the hexadecimal colour of this event
"""
self.COLOUR[event_type]
# now this would return True
my_error_event.colour == "FF0000"