2013-12-07 168 views
1

我目前正試圖在Django中實現狀態模式。把這些模型例如:狀態模式 - 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

不要創建狀態模型,如果聯署只能是兩個「開放」和「封閉」,可以使狀態字段在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() 
+0

如果我希望我的狀態有不同的行爲呢?我正在尋找一些simalar,但使用模型:https://github.com/faif/python-patterns/blob/master/state.py – XuoriG