0

How can i enable or disable actions according to the value of a field.For example In my model I have a status field which can have either of the value 'activate','pending','expired'.I am making a action which set the status equals to 'activate'.Know I want the action to be enable only if status is 'pending'.

4

3 回答 3

1

这是策略状态设计模式的某种组合。

您将为操作定义方法函数,并且您希望该方法函数对模型实例的状态敏感。

这就是我们所做的。

class SpecialProcessing( object ):
    def __init__( self, aModelObject ):
        self.modelObject= aModelObject
    def someMethod( self ):
        pass

class SpecialProcessingActivate( SpecialProcessing ):
    def someMethod( self ):
        # do work if possible or raise exception of not possible

class SpecialProcessingPending( SpecialProcessing ):
    def someMethod( self ):
        # do work if possible or raise exception of not possible

class SpecialProcessingExpired( SpecialProcessing ):
    def someMethod( self ):
        # do work if possible or raise exception of not possible

class MyObject( models.Model ):
    status = models.CharField( max_length = 1 )
    def setState( self ):
        if self.status == "a":
            self.state = SpecialProcessingActivate(self)
        elif self.status == "p":
            self.state = SpecialProcessingPending(self)
        elif self.status == "x":
            self.state = SpecialProcessingExpired(self)
        else:
            raise Exception( "Ouch!" )
    def doSomething( self ):
        self.setState()
        self.state.someMethod()

这样,我们可以自由地添加新的状态(和状态转换规则),而不会过多地干扰模型类。

于 2009-05-11T14:30:12.177 回答
0

管理操作方法为您提供查询集。只需为待处理打一个排除或过滤器

于 2009-05-11T14:33:28.753 回答
-1

我认为使用查询集是个好方法

于 2009-05-12T07:44:46.823 回答