这段代码假设您有一个名为Student的Django模型,其中包含字段lrn和lastname。它创建一个标题为“LRN”和“姓氏”的CSV文件,并将学生模型中的数据写入该文件。HttpResponse对象用于返回CSV文件作为对用户请求的响应。
import csv
from django.http import HttpResponse
from myapp.models import Student
def exportStudentList(request):
students = Student.objects.all()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="Students.csv"'
writer = csv.writer(response)
writer.writerow(['LRN', 'Last Name'])
for student in students:
writer.writerow([student.lrn, student.lastname])
return response