Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

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
question from:https://stackoverflow.com/questions/65936093/django-model-related-list-with-list-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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 }}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...