Home > Software engineering >  Filter list view based on foreign key of another model
Filter list view based on foreign key of another model

Time:03-05

I have three models, subjects, topics and study days. I want to display the study days in a list view but just show study days with different topics connected to the same subject.

This is my model structure

class Subject(models.Model):
    name = models.CharField(max_length=100, null=False)

 
class Topic(models.Model):
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
    name = models.CharField(max_length=100, null=False)

 
class StudyDay(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    ...
    

I have tried this in one of the views and it filters correctly but it removes the data previously showing up associated with the study day, so it does not work correctly.

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['study'] = context['study'].filter(student=self.request.user)
        context['study'] = Topic.objects.filter(subject=3) # This is the line where I try to filter
        return context

So the question is, is there any way for me to filter through the objects in the StudyDay model based on which subject the topic in the study day belongs to?

CodePudding user response:

I think you might want to use __ (double underscore) to access the attributes of your ForeignKeys in filter. See the Django docs about filtering.

So in this specific case you could get StudyDays by Subject if you do:

context['study'] = StudyDay.objects.filter(student=self.request.user, topic__subject__pk=3)
  • Related