pri*_*vex 5 python django recursion django-models django-orm
我使用 Django 的.only()构造来仅查询我需要的列。
前任。
Trainer.objects.filter(id__in=ids).only('id', 'lives')
这是我写的一个简单的例子来重现这个:
class BaseTrainer(models.Model):
mode = models.IntegerField(help_text="An integer")
def __init__(self, *args, **kwargs):
super(BaseTrainer, self).__init__(*args, **kwargs)
self._prev_mode = self.mode
class Trainer(BaseTrainer):
name = models.CharField(max_length=100, help_text="Name of the pokemon")
trainer_id = models.CharField(max_length=10, help_text="trainer id")
badges = models.IntegerField(help_text="Power of the pokemon (HP)")
lives = models.PositiveIntegerField(default=sys.maxsize)
unique_together = ("name", "trainer_id")
def __init__(self, *args, **kwargs):
super(Trainer, self).__init__(*args, **kwargs)
self._temp = self.lives
@classmethod
def test(cls):
t = Trainer.objects.only('trainer_id').all()
print(t)
Run Code Online (Sandbox Code Playgroud)
我只需要 id 和 name 字段,这是肯定的。原因是maximum recursion depth exceeded什么?
原来,原因maximum recursion depth exceeded是因为从模型继承和构造函数覆盖。
正如你在代码中看到的,
self._prev_mode = self.mode
我们尝试mode在超模型类的构造函数中访问。所以,即使我们不需要这个字段供我们使用,我们仍然必须.only()在每个这样的模型调用中包含它。
但是,根据文档,.only()在最坏的情况下应该进行另一个数据库查询以获取字段值,为什么要递归?
好吧,请注意这个字段是在父模型的构造函数中访问的。这就是问题所在。每次都无法在构造函数中读取该值,因此尝试从数据库中获取该值。再次调用构造函数,递归循环一直持续到 python 停止它。
无论如何,通过mode在.only()调用中添加 也解决了这个问题。
Trainer.objects.filter(id__in=ids).only('id', 'name', 'mode')
| 归档时间: |
|
| 查看次数: |
1129 次 |
| 最近记录: |