【问题标题】:Django python iteration through a query set errorDjango python迭代通过查询集错误
【发布时间】:2017-07-04 17:35:22
【问题描述】:

给我带来问题的代码

   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 集再次只提供最多 2 的输出。什么是错误?

【问题讨论】:

    标签: python django django-views


    【解决方案1】:

    MultiValueDict 有一个get 方法。这也出现在标准字典中。它可以帮助您从 dict 中获取一个值,并在它不存在时提供一个默认值。

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

    一般来说,

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

    【讨论】:

      猜你喜欢
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 2016-10-11
      相关资源
      最近更新 更多