jake wong
jake wong

Reputation: 5228

how to update django database entry based on request.POST data

I am working with django on updating my QueryDict into the database. This QueryDict comes from a request.POST method via the html interface.

<QueryDict: {'csrfmiddlewaretoken': ['foo'], 'student_attend': ['Select', 'Select', 'Select'], 'final_student_pk': ['7', '8', '12'], 'submit_student_attendance': ['']}>

What I was attempting to do, was to update my database object student_attend column based on the final_student_pk value. Meaning to say, I was attempting the below:

if 'submit_student_attendance' in request.POST:
    to_update = AddNewSchedule.objects.filter(pk=request.POST['final_student_pk'])
    to_update.update(student_attend=request.POST['student_attend'])

This does do the job of updating my AddNewSchedule database table. However, it only updates the last pk item. (ie: it only updates item 12 in the database). It does not loop through pk 7 and pk8 to update the database as well.

How can I resolve this?

Upvotes: 1

Views: 2311

Answers (2)

MD. Khairul Basar
MD. Khairul Basar

Reputation: 5110

You can not do this in one query because the values are unique for each instance. Try looping through instances and updating one at a time. You can use transaction.atomic to reduce db overhead.

if 'submit_student_attendance' in request.POST:
    id_list = request.POST.getlist('final_student_pk')
    instance_list = request.POST.getlist('student_attend')

    with transaction.atomic():
        for instance, id in zip(instance_list, id_list):
            to_update = AddNewSchedule.objects.filter(pk=id)
            to_update.update(student_attend=instance)

See this answer for more details.

Upvotes: 1

jake wong
jake wong

Reputation: 5228

Turns out the answer was pretty simple.. All I had to do was to use getlist. I made reference here: https://kite.com/python/docs/django.http.request.QueryDict.

    if 'submit_student_attendance' in request.POST:
        print(request.POST.getlist('student_attend'), request.POST.getlist('final_student_pk'))
        from django.db import transaction
        for key, value in zip(request.POST.getlist('final_student_pk'), request.POST.getlist('student_attend')):
            with transaction.atomic():
                to_update = AddNewSchedule.objects.filter(pk=key)
                to_update.update(student_attend=value)

Upvotes: 1

Related Questions