MarkO
MarkO

Reputation: 795

Django updating a status from within a model

I want a way to update the status in a model field when my process below is complete.

views.py

 #If we had a POST then get the request post values.
    if request.method == 'POST':
        batches = Batch.objects.for_user_pending(request.user)
        for batch in batches:
            ProcessRequests.delay(batch)

So I'm thinking of doing something like this in the view...

batch.complete_update()

My issue is, in my models as I'm not sure how, and just need a little help.

This is what I have done so far...

I created

STATUSES = (
    ('Pending', 'Pending'),
    ('Complete', 'Complete'),
    ('Failed', 'Failed'),
    ('Cancelled', 'Cancelled'),
)

then a model function called def complete_update(self):, but I'm not sure how to update the field in it with the status above then save it all from within the model.

Thank you in advance.

PS, is this the right way to go about it?

Upvotes: 0

Views: 1013

Answers (1)

Matt Camilli
Matt Camilli

Reputation: 674

class Batch(model.Model):
    STATUSES_CHOICES = (
        ('Pending', 'Pending'),
        ('Complete', 'Complete'),
        ('Failed', 'Failed'),
        ('Cancelled', 'Cancelled'),
    )
    status = models.CharField(max_length=25, choices=STATUS_CHOICES)
    # The rest of the fields..

    def complete_update(self):
        self.status = 'Complete'
        self.save()

That should do it

Edit: As mentioned by karthikr a post_save might be a better way to go about this

Upvotes: 1

Related Questions