Home > other >  How to display related One to Many Instances in ListView?
How to display related One to Many Instances in ListView?

Time:12-22

I want to display all belonging Instances of model Report referenced to model Module referenced to model Course. Therefore I implemented three Models related via Foreignkey.

class Course(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=200, blank=True, null=True)
class Module(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=200, blank=True, null=True)
    course_id = models.ForeignKey(
        Course,
        null=True,
        on_delete=models.SET_NULL,
        related_name="modules",
        default=uuid.uuid4,
    )
class Report(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=200, blank=True, null=True)
    module_id = models.ForeignKey(
        Module,
        null=True,
        on_delete=models.SET_NULL,
        related_name="reports",
        default=uuid.uuid4,
    )

I want to display model Module referenced to model Course in CourseDetailView(DetailView):

Here is what I implemented:

class CourseDetailView(DetailView):
    model = Course
    context_object_name = "course"
    template_name = "course/course_detail.html"
    fields = ["title", "description"]

    def get_context_data(self, **kwargs):
        context = super(CourseDetailView, self).get_context_data(**kwargs)
        context["courses"] = Course.objects.filter(pk=self.kwargs.get("pk"))
        return context

and I get the instance belonging to itsself.

If I change the context to:

context["modules"] = Module.objects.all()

and iterate over modules in course_detail.html:

    {{ course.description|safe }}

    {% for module in modules %}
    <div>
        <h2><a href="{{ module.get_absolute_url }}">{{ modules.title }}</a></h2>
    </div>
    {% endfor %}

I'll get all instances of Module but I want only the ones related to the specific Course.

I know I have to filter context["modules"] but I don't know how to do it.

Due to the fact that I want to display the modules in CourseDetailView I am not able to get module.pk via super(CourseDetailView, self).get_context_data(**kwargs).

Many thanks in advance

CodePudding user response:

As far as I understood you need smth like Module.objects.filter(course_id=id), where id is the id of specific Cource. This queryset is a common case. As you said in comments for your case needed: Module.objects.filter(course_id=self.object)

  • Related