Django python迭代通过查询集错误

时间:2017-07-04 17:35:22

标签: python django django-views

给我问题的代码

   pk = request.POST['pk']
    medrec = MedicalRec.objects.get(pk=pk)
    med = Medicine.objects.filter(medicalrec=medrec)
    for f in med:
              print("med check")
              print(f.pk)
              print(f.stockpk)
     for ed in med:
                print("printing dtock")
                print(ed.stockpk)
                print("end of doc")
                a= pks()
                a.pk = ed.stockpk
                a.count = request.POST[str(ed.pk)]
                ls.append(a)
     for l in ls:
           print(l.pk)
           print(l.count)
     for n in ls:
           s= Stock.objects.get(pk=n.pk)
           print(s.name)
           s.quantity = s.quantity- int(n.count)
           s.save()

            return redirect('/billing')

输出

med check
3
1
med check
4
2
med check
5
3
3
printing dtock
1
end of doc
printing dtock
2
end of doc
Internal Server Error: /mbill/
Traceback (most recent call last):
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__
    list_ = super(MultiValueDict, self).__getitem__(key)
KeyError: '4'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
    response = get_response(request)
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\Develop\web\ayur\main\views.py", line 136, in mbill
    a.count = request.POST[str(ed.pk)]
  File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__
    raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'4'"

我无法找到错误。迭代只是在中间停止。相同的med查询集直到输出直到3,但med set再次输出最多为2.错误是什么?

1 个答案:

答案 0 :(得分:0)

MultiValueDict有一个get方法。这也存在于标准的dicts上。它可以帮助您从字典中获取值,并提供默认值(如果它不存在。)

a.count = = request.POST.get(str(ed.pk), <default_value>)

一般来说,

my_var = dict.get(<key>, <default>)