[英]How to export csv file after search data in Django 2?
I have a search function that returns json via ajax, but I also want to export the data to a csv file. 我有一个搜索功能,可通过ajax返回json,但我也想将数据导出到csv文件中。
It occurred to me to do another function to export the data, which brings the search function 我想到做另一项功能来导出数据,这带来了搜索功能
I'm doing it like this: 我正在这样做:
def search(request):
date = request.GET.get('date')
queryset = List.objects.filter(date=date)
data = serializers.serialize('json', queryset)
return HttpResponse(data, content_type='application/json')
def export_to_csv(request):
data = search(request)
# But that does not bring the search data
print(data)
# <HttpResponse status_code=200, "application/json">
I hope you understand my question, some ideas or suggestions? 希望您能理解我的问题,想法或建议?
Maybe you can try with simply extracting the logic which retrieves and serializes the data into a helper function, which can be a part of your views.py
(or, probably a better approach, moved to a helper/utility module) eg: 也许您可以尝试简单地提取将数据检索并序列化为帮助程序功能的逻辑,该逻辑可以是您的
views.py
的一部分(或者可能是更好的方法,移至帮助程序/实用程序模块),例如:
def get_search_data(date=None):
queryset = List.objects.all()
if date:
queryset = queryset.filter(date=date)
return serializers.serialize('json', queryset)
def search(request):
data = get_search_data(request.GET.get('date'))
return HttpResponse(data, content_type='application/json')
def export_to_csv(request):
data = get_search_data()
...
print(data)
# <HttpResponse status_code=200, "application/json">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.