Django activities
How to enable or disable actions according to the field value. For example, in my model, I have a status field that can be either "activate", "pending", "expired". I am doing an action that sets the status to "activate". Now I want the action to be enabled only if the status is "pending".
0
a source to share
3 answers
This is some combination of the Strategy and State templates .
You will be defining method functions for an action, and you want this method function to be sensitive to the state of your model instance.
This is what we do.
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()
This way we can add new states (and state transition rules) freely without bothering the model class too much.
+1
a source to share