在這種特殊情況下,我會將十六進制顏色代碼存儲在模型中的字段中。
本質:
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"
有多少類型的事件,你希望有? – Matt 2013-02-21 18:51:57
還有12條左右。 – 2013-02-21 18:52:19