我创建了一个Elasticsearch查询,该查询可以为我提供正确的结果,现在我想将结果发送为搜索API的响应。
我尝试将响应返回为
return JsonResponse(response, status=200)
return Response(response, safe=False) #error response is not JSON serializable
return HttpResponse(
json.dumps(
{"key": response.title}
),
status=200,
content_type="application/json"
) #AttributeError: 'Response' object has no attribute 'title'
我的代码
def search(request):
if request.method=='GET':
q = request.GET.get('q')
if q:
p = Q("multi_match", query=q, fields=['title', 'preview_path'])
s = PostDocument.search().query(p)
response = s.execute()
else:
response = ''
return HttpResponse(response)
我的PostDocument代码
posts = Index('media')
@posts.doc_type
class PostDocument(DocType):
print('documents.py')
class Meta:
model = Media
fields = [
'title',
'description',
'start_date',
'end_date',
'status',
'media_source',
'on_front_page',
'thumbnail_path',
'preview_path',
'published_date',
'created_at',
'updated_at',
]
预期结果: 我要将响应作为“ Json响应”发送。
实际结果,当我使用 打印(响应)
<Response: [{'start_date': datetime.datetime(2019, 1, 30, 0, 0), 'status...}]>
答案 0 :(得分:1)
您可以使用json.dumps创建JSON响应:
HttpResponse(
json.dumps(
{"key": response.key}
),
status=200,
content_type="application/json"
)
编辑:由于您的响应对象不是对象而是对象列表,因此您需要执行以下操作:
response_list = []
for item in response:
response_list.add(
{
"title": item.title,
"description": item.description
}
)
return HttpResponse(
json.dumps(response_list),
status=200,
content_type="application/json"
)