State Pattern - Django models

1.8k views Asked by At

I'm currently trying to implement the state pattern in Django. Take these models for example:

class Restaurant(models.Model):
    name = models.CharField()
    # other fields here ...


class State(models.Model):
    pass

class StateOpen(State):
    def toggle_open_closed():
        pass

class StateClosed(State):
    def toggle_open_closed():
        pass

now how can I make my restaurant have a state, and this state can either be a StateOpen or StateClosed?

Edit: Ideally I would want to be able to do something like that:

r = Restaurant(name='whatever')
r.state.doSomething()

# doSomething() being a function that each state child class has,
# but implemented differently
1

There are 1 answers

1
ndpu On

Dont create models for state if sates can be only two 'open' and 'closed', you can make state field in Restaurant model:

class Restaurant(models.Model):
    name = models.CharField()
    state = models.BooleanField(default=False)

    def toggle_open_closed(self):
        self.state = not self.state
        self.save()

You can also define states us predefined list of states and IntegerField in model:

RESTARAUNT_STATE = (
    (0, 'Open'),
    (1, 'Closed'),
    (2, 'Didnt decided yet, come here later!'),

    # you can define more states later
)

class Restaurant(models.Model):
    name = models.CharField()
    state = models.IntegerField(choices=RESTARAUNT_STATE)

And if you're really need separate model for states, you can make it of course, but toggle_state function must be in Restaraunt model.

class State(models.Model):
    name_of_state = models.CharField()

class Restaurant(models.Model):
    name = models.CharField()
    state = models.ForeignKey(State)

    def toggle_state(self):
        self.state = State.objects.get(...)
        self.save()