我想在mysql查詢後導出一個csv文件。我得到以下錯誤;在Django上的Mysql錯誤
(1064,「您的SQL語法錯誤;檢查對應於你的MySQL服務器版本,在1號線附近使用‘’正確的語法手冊」)
import csv
from django.db import connections
from django.http import HttpResponse
from django.views.generic import ListView
from testing.models import TrRunSummary, TrDetails
class ExportCsv(ListView):
"""Displays the different tests performed on the specified test request"""
template_name = 'testing/tr_export_csv.html'
context_object_name = 'export_csv'
def get_context_data(self, **kwargs):
context = super(ExportCsv,self).get_context_data(**kwargs)
context['tr_info'] = self.tr_info()
return context
def get_queryset(self):
qtr_id = self.kwargs['trID']
s = str(qtr_id)
print s
print type(s)
cursor = connections['default'].cursor()
query ="SELECT results_stb_id, results_stbs.stb_id, stb_inv.mac_add, "
"test_functionality.test_functionality_code, test_cases.test_case_no, "
"SCRIPT.option_name AS script_result, POST.option_name AS post_result, "
"results_tests.started, results_tests.stopped, results_tests.test_duration, builds.baseline, "
"builds.build_type, stb_hw_info.stb_type, defects.defect_name, parser_output, log_url, "
"script_health_score, post_health_score FROM results_stbs "
"JOIN tr_test_cases "
"ON tr_test_cases.tr_test_case_id=results_stbs.tr_test_case_id "
"JOIN test_cases "
"ON test_cases.test_case_id=tr_test_cases.test_case_id "
"JOIN test_functionality "
"ON test_functionality.test_functionality_id=test_cases.test_functionality_id "
"LEFT JOIN stb_inv "
"ON results_stbs.stb_id=stb_inv.stb_id "
"LEFT JOIN result_options AS SCRIPT "
"ON results_stbs.script_result=SCRIPT.result_option_id "
"LEFT JOIN result_options AS POST "
"ON results_stbs.post_result=POST.result_option_id "
"JOIN results_tests "
"ON results_stbs.results_test_id=results_tests.results_test_id "
"JOIN builds "
"ON builds.build_id=results_stbs.build_id "
"JOIN stb_hw_info_ids "
"ON stb_hw_info_ids.stb_hw_info_ids_id=results_stbs.stb_hw_info_ids_id "
"JOIN stb_hw_info "
"ON stb_hw_info.stb_hw_info_id=stb_hw_info_ids.stb_hw_info_id "
"LEFT JOIN defects_tests "
"ON results_tests.results_test_id=defects_tests.results_test_id "
"LEFT JOIN defects "
"ON defects.defect_id=defects_tests.defect_id "
"WHERE tr_test_cases.tr_id = '%s' AND script_result IN (1, 3, 8) "
"OR tr_test_cases.tr_id = '%s' AND post_result IN (1, 3, 8) "
"ORDER BY results_stb_id ASC " % (s, s)
cursor.execute(query)
print cursor
def tr_info(self):
tr_id = self.kwargs['trID']
tr_info = TrDetails.objects.get(
tr_id=tr_id,
)
return tr_info
class SavedCsvView(ExportCsv):
"""
Subclass of above view, to produce a csv file
"""
template_name = 'TR_Export.csv'
content_type = 'text/csv'
我的查詢在Python腳本上工作正常。當我添加Django視圖時,它給我錯誤。任何幫助將不勝感激。
請貼全追蹤誤差 –
你可以用這種方式https://docs.djangoproject.com/en/1.10執行直接的SQL查詢/ topics/db/sql /#executable-custom-sql-directly –
用'\'結束帶有字符串的行或使用三重引號或用'()'圍繞'='後面的所有內容創建一個多行串。你是如何做到的,只有第一部分進入了字符串。 –