Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango - optimization question
    primarykey
    data
    text
    <p>If you have some models:</p> <pre><code>class Teacher(models.Model): name = models.CharField(max_length=50) class Student(models.Model): age = models.PositiveIntegerField() teacher = models.ForeignKey(Teacher, related_name='students') </code></pre> <p>and you use it like this:</p> <pre><code>&gt;&gt;&gt; student = Student.objects.get(pk=1) &gt;&gt;&gt; student.teacher.name # This hits the database 'Some Teacher' &gt;&gt;&gt; student.teacher.name # This doesn't (``teacher`` is cached on the object) 'Some Teacher' </code></pre> <p>That's awesome. Django caches the related object so that you can use it again without having to abuse your database.</p> <p><strong>But</strong>, if you use it like this:</p> <pre><code>&gt;&gt;&gt; teacher = Teacher.objects.get(pk=1) &gt;&gt;&gt; for student in teacher.students.all(): # This hits the database ... print(student.age) ... 8 6 &gt;&gt;&gt; for student in teacher.students.all(): # This does too (obviously) ... print(student.age) ... 8 6 </code></pre> <p>There's no caching or efficient access to related objects this direction.</p> <p><strong>My question is thus:</strong> Is there a built-in (or non-problematic way) to backward access related objects in an efficient way (a cached way), like you can in the <code>student.teacher</code> example above?</p> <p>The reason I want this is because I have a model with multiple methods that need access to the same related objects over and over, so a page that should have 12 queries ends up with about 30.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload