3
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) File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 169, in get_response response = self.handle_uncaught_exception(request, resolver , sys.exc_info()) 文件 "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", 第 218 行, 在 handle_uncaught_exception 返回回调(request, **param_dict) 文件“/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py”,第 93 行,在 _wrapped_view 响应 = view_func(request, *args, **kwargs) 文件“/usr/local/ lib/python2.6/dist-packages/django/views/defaults.py", line 30, in server_error t = loader.get_template(template_name) # 你需要创建一个 500.html 模板。文件“/usr/local/lib/python2.6/dist-packages/django/template/loader.py”,第 157 行,

4

2 回答 2

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)

你可以在这里阅读更多。

于 2013-11-06T13:17:54.393 回答
0

您当前正在获取所有对象(通过执行all()),然后您将其恢复为filter(id=report_id).

您只能使用以下方式获取所有对象all()

report_qs = CustomReport.objects.all()
于 2013-11-06T12:19:15.887 回答