Django对待列表和python有什么不同?输出被HttpResponse损坏?

2024-03-28 16:29:23 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能是一个非常明显的问题。我使用return HttpResponse()来了解我正在调试的变量,实际上我正在构建一个查询列表,但是当我在Django中附加到一个列表时,它的行为与Python不同,我不知道这是否是一个显示问题。你知道吗

在Django

QueryList = []
for item in spltfieldvalues:
    strpitem = item.strip('[],')
    queryitem = Q(fieldname+'__contains='+strpitem)
    QueryList.append(queryitem)

应该给出一个逗号分隔的列表。但是,当我使用HttpResponse输出时,我只得到以下结果:

AND: MyAgePref__contains=u'_U18')(AND: MyAgePref__contains=u'_O76')

我希望这两个选项以逗号分隔,如[Q(A), Q(B)]

只是在附加字符串上尝试一下,即QueryList.append('A')在输出上给出AA,没有逗号分隔。但是在python控制台上,它工作得很好,我得到了['A','A']HttpResponse是否损坏了输出?这很奇怪,因为我用它来观察JSON,一切似乎都很好。你知道吗


Tags: anddjangoin列表forreturnitem逗号
1条回答
网友
1楼 · 发布于 2024-03-28 16:29:23

您正在将一个列表传递给HttpResponse,而列表是一个迭代器。当您这样做时,迭代器被视为一个字符串序列来写入浏览器,而不是作为一个对象来转换为字符串。从^{} documentation

Finally, you can pass HttpResponse an iterator rather than strings. If you use this technique, the iterator should return strings.

further down the page

content should be an iterator or a string. If it’s an iterator, it should return strings, and those strings will be joined together to form the content of the response. If it is not an iterator or a string, it will be converted to a string when accessed.

首先将列表转换为字符串,然后发布:

HttpResponse(str(QueryList))

相关问题 更多 >