Michael
Michael

Reputation: 832

Django, best practice to execute an action for each instance of a model

here's my question.

I have a model like that

class ActionQueue(models.Model):
    action_type = models.CharField(max_length=30, choices=ACTION_QUEQUE_TYPE)

    def execute(self):
        if self.action_type == 'exam':
                ... do something ...

What's the best way to execute the function "execute" for each instance of ActionQueue ? Currently i'm using a for..in:

 for action in ActionQueue.objects.all():
     action.execute()

Maybe there is a better way (in terms of performances) to achieve the same result..

Thank you

Upvotes: 0

Views: 97

Answers (1)

iMom0
iMom0

Reputation: 12931

I think what you want is

actions = ActionQueue.objects.filter(action_type='exam')

then

actions.update(...)

or

action_list = list(actions)
# do something with action_list
[do_something(action) for action in action_list]

Upvotes: 1

Related Questions