views:

120

answers:

3

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
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
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
Agreed.........
phillc
A: 

Admin action methods provide you a queryset. Just slap an exclude or filter for pending

phillc
A: 

i think using queryset is good approach

ha22109
That is a useless answer.
drozzy