Django REST框架。我如何在CSV中制作导出模型

时间:2019-07-03 19:47:03

标签: django django-models django-rest-framework export-to-csv

我有以下型号:

inner class SwipeCallback() : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.RIGHT) {
        override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
            val item1 = getItem(viewHolder.adapterPosition)
            val item2 = getItem(target.adapterPosition)
            if (item1 != null && item2 != null) {
                //BASICALLY JUST SWAPPING THE TWO POSITIONS ON THE OBJECTS but not doing anything with the adapter array because the PagedListAdapter doesn't allow me to modify the array as far I know.
                swapItems(item1,item2)

                }
                return true
            }
            return false
        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

        override fun isLongPressDragEnabled(): Boolean {
            return false
        }

        override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
            super.onSelectedChanged(viewHolder, actionState)
            if (actionState == ACTION_STATE_DRAG) {
                viewHolder?.itemView?.alpha = 0.5f
            }
        }

        override fun clearView(recyclerView: RecyclerView,
                               viewHolder: RecyclerView.ViewHolder) {
            super.clearView(recyclerView, viewHolder)

            viewHolder?.itemView?.alpha = 1.0f

            //THIS IS WHERE I UPDATED THE DB, currentList is the PagedListAdapter array. This is an inner class of my PagedListAdapter.
            currentList?.let {updateList(it) }
        }
    }

还有我们:

class Student(models.Model):
   first_name = models.CharField(verbose_name='student first name', max_length=64)
   last_name = models.CharField(verbose_name='student last name', max_length=64)
   email = models.EmailField()

class Meta:
    db_table = 'student'

def __str__(self):
    return self.first_name + ' ' + self.last_name

class Course(models.Model):
   name = models.CharField(max_length=255)
   description = models.TextField()
   start_date = models.DateField(null=True, blank=True, default=None)
   end_date = models.DateField(null=True, blank=True, default=None)

class Meta:
    db_table = 'course'

def __str__(self):
    return self.name

class CourseParticipant(models.Model):
    course = models.ForeignKey(Course, related_name='courses', on_delete=models.CASCADE)
    student = models.ForeignKey(Student, related_name='student_name', on_delete=models.CASCADE)
    completed = models.BooleanField(null=False, default=False)

    class Meta:
        db_table = 'course_participant'

    def __str__(self):
        return self.course, self.student

]

我需要以以下格式在csv中导出一些数据:

  • 学生全名
  • 为学生分配的课程数量
  • 按学生完成的课程数量

例如:

urlpatterns = [
    path('course', CourseAPIView.as_view()),
    path('course/<int:pk>/', CourseAPIDetailView.as_view()),
    path('student', StudentAPIView.as_view()),
    path('student/<int:pk>/', StudentAPIDetailView.as_view()),
    path('student/assigned_to_course', StudentAssignedToTheCourseAPIView.as_view()),
    path('student/assign_student_to_course', StudentAssignToCourse.as_view()),
    path('student/assigned_to_course/<int:pk>/', StudentAssignedToTheCourseDetailView.as_view()),
    path('student/report/<int:pk>/', StudentReportView.as_view()),

因此,应该使用哪种视图。我的意思是,我如何获取学生全名等数据。我将非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您可以使用Python的csv模块。


起初,我建议在您的full_name模型中将Student定义为一个属性,因为这样会更清楚:

class Student(models.Model):
    ...

    @property
    def full_name(self):
        return self.first_name + ' ' + self.last_name

然后,您可以为作业定义一个简单的APIView

import csv

from django.http import HttpResponse

from rest_framework.views import APIView


class ExportCSVStudents(APIView):
    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="export.csv"'

        writer = csv.writer(response)

        for student in Student.objects.all():
            assigned_courses = CourseParticipant.objects.filter(student=student)
            completed_courses = assigned_courses.filter(completed=True)

            row = ','.join([
                student.full_name,
                assigned_courses.count(),
                completed_courses.count()
            ])

            writer.writerow(row)

       return response

在您将其注册到urlconf中并通过简单的HTTP GET访问后,这应该会自动下载包含所需数据的文件export.csv