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
Dont create models for state if sates can be only two 'open' and 'closed', you can make state field in
Restaurant
model:You can also define states us predefined list of states and
IntegerField
in model:And if you're really need separate model for states, you can make it of course, but
toggle_state
function must be inRestaraunt
model.