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'.
A:
This is some combination of the Strategy and State design patterns.
You'll be defining method functions for the action, and you'll want that method function to be sensitive to the state of your model instance.
Here's 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 disturbing the model class too much.
S.Lott
2009-05-11 14:30:12
This would evaluate the queryset, causing 1 query or action per row. If you use a filter you would remove the uneeded objects and allow you to modify the entire queryset with one swing.
phillc
2009-05-11 14:36:02
Depends on when and how the change occurs. In many instances the state change is A Big Deal, and the row-by-row query evaluation here is central to what's going on and this query is the heart of the transaction.
S.Lott
2009-05-11 15:59:28
Agreed.........
phillc
2009-05-11 18:57:38
A:
Admin action methods provide you a queryset. Just slap an exclude or filter for pending
phillc
2009-05-11 14:33:28