Workflows in Django
I'm going to cover a simple, but effective, utility for managing state and transitions (aka workflow). We often need to store the state (status) of a model and it should only be in one state at a time.
Booleans for states
Mutually exclusive states ... sort of finite, but the number of states increases with each bool:
Brittle and too many states to check.
The behavior of state machines can be observed in many devices in modern society which perform a predetermined sequence of actions depending on a sequence of events with which they are presented.
CharField with defined choices
state = CharField(
default=1,
choices=[(1, "draft"), (2, "approved"), (3, "published")]
)
Define methods to change state:
def publish(self):
self.state = 3
email_sombody(self)
self.save()
def approve(self):
self.state = 2
self.save()
Better, but ...
https://github.com/kmmbvnr/django-fsm
P.S. RoR has similar apps too
protected=True
state = FSMField(
default=State.DRAFT,
verbose_name='Publication State',
choices=State.CHOICES,
protected=True,
)
(alternatives FSMIntegerField
, FSMKeyField
)
@transition(field=state, source=[State.APPROVED, State.EXPIRED],
target=State.PUBLISHED,
conditions=[can_display])
def publish(self):
'''
Publish the object.
'''
email_the_team()
update_sitemap()
busta_cache()
What does this get us?
./manage.py graph_transitions -o example-graph.png fsm_example.PublishableModel
Something a bit more complex:
https://github.com/gadventures/django-fsm-admin
https://github.com/gizmag/django-fsm-log
If you'd like your state transitions stored in something other than the admin history.
Not much out there. django-fsm has the most activity.
Craig Nagy @nagyman G Adventures - Software Engineering, eComm Mgr.