无法通过查询对象检索值

时间:2013-11-06 12:09:16

标签: python django apache

report_qs = CustomReport.objects.filter(id=report_id)

report_qs store below output

输出

{
    "Locator__employer_state": "AR",
    "data_model_name": [
        "Locator",
        "PatientProfile"
    ]
}

问题:如何从Python上面的输出中获取所有值和键?

当我尝试从上面的输出中访问键和值时,我收到以下错误:

文件“/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py”,第283行,在运行中     self.result = application(self.environ,self.start_response)   文件“/usr/local/lib/python2.6/dist-packages/django/core/handlers/wsgi.py”,第272行,致电     response = self.get_response(request)   在get_response中输入文件“/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py”,第169行     response = self.handle_uncaught_exception(request,resolver,sys.exc_info())   在handle_uncaught_exception中的文件“/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py”,第218行     返回回调(request,** param_dict)   在_wrapped_view中输入文件“/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py”,第93行     response = view_func(request,* args,** kwargs)   在server_error中输入文件“/usr/local/lib/python2.6/dist-packages/django/views/defaults.py”,第30行     t = loader.get_template(template_name)#您需要创建500.html模板。   在get_template中输入文件“/usr/local/lib/python2.6/dist-packages/django/template/loader.py”,第157行     template,origin = find_template(template_name)   在find_template中输入文件“/usr/local/lib/python2.6/dist-packages/django/template/loader.py”,第138行     提升TemplateDoesNotExist(名称) TemplateDoesNotExist:500.html

2 个答案:

答案 0 :(得分:0)

您目前正在获取所有对象(通过执行all()),然后您将其带回filter(id=report_id)的对象。

您只需使用all()

即可获取所有对象
report_qs = CustomReport.objects.all()

答案 1 :(得分:0)

这是一本字典,因此您可以使用各自的键访问其值,如下所示:

report_qs = CustomReport.objects.all().filter(id=report_id)

for res in report_qs:
    print res
    # Print Locator_employer_state
    print "Locator Employer State: " + str(res["Locator_employer_state"])
    # Print data_model_name_value
    string_ = ""
    for item in res["data_model_name"]: ### this loop is just for creating a nice string to print
        string_ += str(item) + ", "
    print "Data Model Name: " + string_

如果您只想访问值,也可以使用.values()方法:

for res in report_qs:
    print str(res.values())

只是为了涵盖所有方法,您可以使用.items()方法迭代字典:

for res in report_qs:
   for key, value in res.items():
       print str(key) + ": " + str(value)

您可以阅读更多here