我正在尝试使用与防止 Django 进行过多查询相关的预取,但我无法使其适用于具有继承的模型。
问题是当我用继承遍历模型时,模型实例没有被缓存,并且发出了一个 SQL 查询。
我不确定这是 Django 错误还是我以某种方式滥用它。
这是我的代码:
模型.py:
class ParentBase(models.Model): pass
class Parent(models.Model): pass
class ParentWithBase(ParentBase): pass
class Child(models.Model):
parent = models.ForeignKey('Parent')
parent_with_base = models.ForeignKey('ParentWithBase')
测试用例:
def test_prefetch_error(self):
Child.objects.create(parent = Parent.objects.create(), parent_with_base = ParentWithBase.objects.create())
child = Child.objects.prefetch_related('parent','parent_with_base').all()[0]
with self.assertNumQueries(0):
child.parent # This works just fine - no queries are emitted
with self.assertNumQueries(0):
child.parent_with_base # TEST FAILS HERE - since one query is emitted