简体   繁体   English

如何基于request.POST数据更新Django数据库条目

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

I am working with django on updating my QueryDict into the database. 我正在与django一起updating我的QueryDict updating到数据库中。 This QueryDict comes from a request.POST method via the html interface. QueryDict通过html接口来自request.POST方法。

<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. 我试图做的,是更新我的database object student_attend基于列final_student_pk值。 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. 这确实完成了更新我的AddNewSchedule数据库表的工作。 However, it only updates the last pk item. 但是,它仅更新最后一个pk项。 (ie: it only updates item 12 in the database). (即:它仅更新数据库中的项目12)。 It does not loop through pk 7 and pk8 to update the database as well. 它也不会遍历pk 7pk8来更新数据库。

How can I resolve this? 我该如何解决?

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. 您可以使用transaction.atomic减少数据库开销。

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 = to_update = AddNewSchedule.objects.filter(pk=id)
            to_update.update(student_attend=instance)

See this answer for more details. 有关更多详细信息,请参见此答案

Turns out the answer was pretty simple.. All I had to do was to use getlist . 原来答案很简单。我要做的就是使用getlist I made reference here: https://kite.com/python/docs/django.http.request.QueryDict . 我在这里做了参考: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM