mercredi 15 février 2017

What is the best way to implement the State design pattern in Django model layer?

We have some Tasks and states, that a task might have. You may think of any task tracking app, aka redmine. States are constant and won't change in the future. The possibilities of transition from one state to another are also constant.

class State(models.Model):
    STATE_NEW = 1
    STATE_IN_PROGRESS = 2
    STATE_POSTPONED = 3
    STATE_DONE = 4

    name = models.CharField(
        max_length=50,
        unique=True,
    )

class Task(models.Model):
    name = models.CharField(max_length=255, db_index=True)
    state = models.ForeignKey(State, default=State.STATE_NEW)

What I want is to implement a state design pattern, not to have an ugly changeState method full of conditionals. What is the best way to achieve this in Django?

Aucun commentaire:

Enregistrer un commentaire