grahamie
grahamie

Reputation: 311

how do update a model after the return statement

I have a view when should update the model data as "Sent" after rendering to template. I want to exclude things that are already sent then update the value no (number) as sent then return the data to the template.

the problem is that if i use it as it is it seem to do all three liunes in one go and excludes the no as its been sent,, how can I update it as sent AFTER the data is returned.

def get(self, request, *args, **kwargs):
        lab = request.GET.get('lab', None)

        audit = models.SendAudit.objects.filter(no__exact=labno).exclude(status__contains='sent')

        models.SendAudit.objects.select_related().filter(no__exact=labno).update(status='{Sent}')

        return render(request, self.template_name2, {'audit': audit, 'no': no})

Upvotes: 2

Views: 646

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476719

QuerySets are lazy, so that means that as long as you do not iterate over the query, or call len(…) or consume the queryset in another way, it will not run the query.

You can use list(…) to materialize the QuerySet into a list for example:

def get(self, request, *args, **kwargs):
    lab = request.GET.get('lab')
    qs = models.SendAudit.objects.filter(no=labno)
    audit = list(qs.exclude(status__contains='sent'))
    qs.update(status='{Sent}')
    return render(request, self.template_name2, {'audit': audit, 'no': no})

It howeever does not make much sense to make updates in a GET request. A GET request is not supposed to have side-effects by the HTTP standard. A POST/PATCH/PUT/… request can have side-effects.

Upvotes: 1

Related Questions