关于python:django执行向后关系查询时发生最大递归深度超出错误,当我使用manager时

Django executing backward relation query occurred a maximum recursion depth exceeded error when I use Manager

代码如下:

类源

1
2
3
4
5
6
class CarSource(models.Model):
    status = models.CharField(max_length=1, blank=True, null=True)
    dealer = models.ForeignKey(Dealer, blank=True, null=True, \
                  on_delete=models.SET_NULL, related_name='cars', \
                  verbose_name=u'dealer own this car')
    objects = CarSourceManager()

班商

1
2
class Dealer(models.Model):
    ...

类carsourceManager:

1
2
3
4
class CarSourceManager(models.Manager):
    ''' Manage query in CarSource, filter data that was processed successfully.'''
    def get_query_set(self):
        return super(self.__class__, self).get_query_set().filter(status='S')

当我执行此操作时:

1
2
3
from ... import Dealer
d = Dealer.objects.get(id = 2)
d.cars.all()

出现以下错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
File"/...path..of..error..file../apps/car/managers.py", line 9, in all
return super(self.__class__, self).all().filter(status='S')
File"/...path..of..error..file../apps/car/managers.py", line 9, in all
return super(self.__class__, self).all().filter(status='S')
File"/...path..of..error..file../apps/car/managers.py", line 9, in all
return super(self.__class__, self).all().filter(status='S')
File"/...path..of..error..file../apps/car/managers.py", line 9, in all
return super(self.__class__, self).all().filter(status='S')
File"/...path..of..error..file../apps/car/managers.py", line 9, in all
return super(self.__class__, self).all().filter(status='S')
File"/...path..of..error..file../apps/car/managers.py", line 9, in all
return super(self.__class__, self).all().filter(status='S')
File"/...path..of..error..file../apps/car/managers.py", line 9, in all
return super(self.__class__, self).all().filter(status='S')
RuntimeError: maximum recursion depth exceeded while calling a Python object

我重写了CarSourceManagermodels.Managerget_query_set,显然,它继续自递归地称之为models.Manager。我看了经理的代码,但没弄清楚,请帮帮我。


请参阅以下答案:https://stackoverflow.com/a/18208725/1085511

基本上你不能用

1
super(self.__class__, self)

使用

1
super(CarSourceManager, self)

相反。

相关经理的self.__class__CarSourceManager不同,因此循环。


这就是在调用super时必须显式命名类的原因:

1
return super(CarSourceManager, self).get_query_set().filter(status='S')