djangodjango-modelsdjango-related-manager

Django getting one to many on same query


I need to display a view with Courses with its dependable Lectures on an accordion in html. A Course has many Lectures.

class Course(models.Model):
    title = models.CharField(max_length=1500)
    def __str__(self):
        return self.title

class Lecture(models.Model):
    title = models.CharField(max_length=1500)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    content = models.TextField()

    def __str__(self):
        return self.title

It seems like all the examples I have found. Get the relationship after doing a filter or getting the first object like this:

Course.objects.first().lecture_set.all()

This gets all the lectures for the first one. But I need to get all Courses with all lectures. Something like this:

Course.objects.all().lecture_set.all() or Course.objects.filter('all').lecture_set.all()

This way I could iterate over Courses and then on each Course iterate again with Course.lectures

Does anyone know the best practice to achieve this?


Solution

  • You can use prefetch_related() In your example it would be like Course.objects.all(). prefetch_related('lecture_set') So after that you can iterate all courses and getting its lectures without accessing database. Make sure that you will access it through object itself like:

    {% for course in courses_list %}
         {% for lecture in course.lecture_set.all() %}
    

    There is good library to inspect each request details, like count of database connections per request. So you can optimize your code.

    Hope I hepled.