如果你有一些车型:Django的 - 优化问题
class Teacher(models.Model):
name = models.CharField(max_length=50)
class Student(models.Model):
age = models.PositiveIntegerField()
teacher = models.ForeignKey(Teacher, related_name='students')
并且你使用这样的:
>>> student = Student.objects.get(pk=1)
>>> student.teacher.name # This hits the database
'Some Teacher'
>>> student.teacher.name # This doesn't (``teacher`` is cached on the object)
'Some Teacher'
这真棒。 Django缓存相关对象,以便您可以再次使用它,而不必滥用数据库。
但,如果你使用这样的:
>>> teacher = Teacher.objects.get(pk=1)
>>> for student in teacher.students.all(): # This hits the database
... print(student.age)
...
8
6
>>> for student in teacher.students.all(): # This does too (obviously)
... print(student.age)
...
8
6
有没有缓存或相关对象的有效访问这个方向发展。
我的问题是这样的:有没有一种有效的方式内置(或无问题的方式)向后访问相关的对象(缓存的方式),就像你可以在上面的student.teacher
的例子吗?
我想这是因为我在那一遍遍需要访问同相关对象的多种方法,模型之所以这么说应该有12个查询页面结束了约30
优秀!每次遇到新问题时,你都会遇到同样的问题。你就像我宫城先生,虽然讽刺你的名字是丹尼尔:)再次感谢。 – orokusaki 2010-11-27 19:21:36
在这种情况下select_related()不起作用吗? – jMyles 2010-11-27 20:20:48