외부 함수를 만들어 테이블을 조인하고 다운로드 한 다음 다운로드 한 파일을 가리키는 내 정적 파일에 링크를 제공하여이 문제를 해결합니다.
여기
def database_downloader():
import pymysql # run pip install pymysql if this fails
import sys
import time
import csv
start = time.time()
connect = 0
attempt = 1
while connect==0: #if connection is not secured, will try again in 3 seconds.
try:
print "connecting, attempt "+str(attempt)
conn = pymysql.connect(host='url', port=3306, user='username', passwd='pass', db='db', autocommit=True) #setup our credentials
cur = conn.cursor()
connect = 1
except:
print "try again in 3 seconds"
time.sleep(3)
attempt+=1
continue
print "connected to server in " +str(time.time()-start)+ " seconds."
out_file = open("main_app/static/main_app/reports/output.csv", "wb")
writer = csv.writer(out_file)
sql = "SELECT * FROM main_app_basic_info b LEFT JOIN main_app_add_info a ON a.Student_ID = b.Student_ID;"
cur.execute(sql)
column_names = []
for i in cur.description:
column_names.append(i[0])
writer.writerow(column_names)
for i in cur.fetchall():
writer.writerow(i)
print "Downloading completed in " + str((time.time()-start)) + " seconds."
out_file.close() # you need to close to save before sending
가 그럼 난이 기능을 페이지가로드가 업데이트 다운로드 준비해야 할 때마다 실행, 내 도우미 함수입니다. 이처럼
def index(request):
student_list = basic_info.objects.order_by('-id')[:5]
student_list_full = basic_info.objects.order_by('-id')
context = {'student_list': student_list, 'student_list_full': student_list_full}
database_downloader() # this downloads the database in every refresh to main_app/reports/output.csv
return render(request, 'main_app/index.html', context)
는 마지막으로, 나는
{% load static %}
<div><a href="{% static "main_app/reports/output.csv" %}" download>Click Here to Download to Database</a></div>
나는 아직도이 최선의 해결책이 완벽하게 확실하지 않다, 내 템플릿에이를 추가합니다. 그러나 이것은 내가 지금 할 수있는 능력이며, 잘 작동합니다.
내가 장고 가져 오기/내보내기를 찾고 싶습니다 – Foon