A Handy Ordinal Field Type in Django

Waking up at 3am in the morning and wanting to execute an idea is a good indication that you have chosen the right career. It came to me one early morning that the way I was dealing with ordinal types was clunky, and I needed a type that was orderable, quick to compare, easy to display and not prone to typing errors.

The Enumerated Base Class

The base class has a method to display an ordinal choice, and it must have choices defined in the superclass. An improvement could be to do a check on instantiation that there is a member variable called "choices" that is a list of tuples using an if not hasattr(self, 'choices') raise Exception().
Enumerated Base Class

The Task Status Example

For example, If I have a que of tasks, each task can be:
  1. Pending
  2. Running
  3. Done
  4. Failed
  5. Killed
Task Status Enumerated Type

The Queued Task Model

A queued task has a command, is linked to a cron job if it was queued by one, and has a status to indicate whether it needs to be run, or how it ran. The status value stored is an integer (could be positive integer), which takes up a relatively small amount of memory, and there is a method to display the status which shows the string part of the tuple associated with the task's status.
The Queued Task Model

Processing Tasks

When we want a list of commands that need to be run, we have a simple conditional statement that compares an explicit set of integers given by the enumerated type's choices. Comparing integers is quicker than checking strings, and is less prone to typo errors. Also, if we were comparing strings or characters here, we would have no idea of order, so would have to check multiple conditions.
Checking The Enumerated Type Example