具有列表视图的 Django 模型 related_list

Django model related_list with list view

首先,我有一个学生模型和一个辅导模型。

一个学生模型有上百个咨询模型

我想将每个科目(分类)的最后咨询日期制作成每个学生的列表视图。

如果成功了,老师一眼就能看出谁咨询的时间最长,谁咨询的时间最近。

有什么办法吗?

咨询model.py

class Consultation(models.Model):
    classification = models.CharField(
        max_length=10,
        choices=CLASSIFICATION,  # there are 'korean', 'english', 'math', 'etc ... '
        default='etc',
    )
    content = models.TextField(max_length=1000, blank=False, verbose_name='contentt')
    created_to = models.ForeignKey(
        Student,
        related_name='consultations',
        verbose_name='student',
        on_delete=models.CASCADE
    )
    created_at = models.DateTimeField(default=datetime.now, verbose_name='time')

学生mnodel.py

class Student(models.Model):
    name = models.CharField(max_length=255, verbose_name='이름')

如果可以的话,我想使用 ListView

class StudentList(ListView):
    model = Student
    template_name = 'student/list.html'
    context_object_name = 'students'
    paginate_by = 10
    blah blah blah 


我想做的是这样的

student name last consultation date of korea subject last consultation date of english subject last consultation date of math subject
student name last consultation date of korea subject last consultation date of english subject last consultation date of math subject
student name last consultation date of korea subject last consultation date of english subject last consultation date of math subject
student name last consultation date of korea subject last consultation date of english subject last consultation date of math subject
student name last consultation date of korea subject last consultation date of english subject last consultation date of math subject
class Student(models.Model):
    name = models.CharField(max_length=255, verbose_name='이름')
    
    def last_consult_korean(self):
        last_date=self.consultations.filter(classification='korean').order_by('-created_at').first()
        return last_date.created_at if last_date else ''

在你的模型中写一个像这样的函数,在你的模板调用中像 {{ student.last_consult_korean }}