状态模式 - Django模型

时间:2013-12-07 21:25:17

标签: python django design-patterns django-models state

我目前正在尝试在Django中实现状态模式。以这些模型为例:

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

现在如何让我的餐馆有一个州,这个州可以是StateOpen还是StateClosed?

编辑:理想情况下,我希望能够做到这样的事情:

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

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

1 个答案:

答案 0 :(得分:1)

如果状态只有两个“开放”和“关闭”,则不要为状态创建模型,您可以在Restaurant模型中创建状态字段:

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

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

您还可以在模型中定义州预定义状态列表和IntegerField

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)

如果您真的需要单独的状态模型,那么您当然可以做到,但toggle_state函数必须在Restaraunt模型中。

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()