djangomodeldjango-querysetdjango-select-related

Django model related_list with list view


First, I have a student model and a counseling model.

There are hundreds of consultation models in one student model.

I'd like to make the last consultation date for each subject(classification) into a listview for each student.

If make it , teacher can see at a glance who consulted the longest and who consulted the most recently.

is there any way?

consultation 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')

student mnodel.py

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

I want to user ListView if i can

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


What i want to make is like

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

Solution

  • 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 ''
    

    write a function like this in your model, and in your template call like {{ student.last_consult_korean }}