使用 post-保存信号调用函数的递归错误
Recursion error calling a function using a post-save signal
我有一个 Category 模型,其中 ForeignKey 是 self。
class Category(SEO, MetaData):
parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE)
path = ArrayField(models.IntegerField(), blank=True, null=True)
我引入了路径字段,以避免在小部件中进行递归,并对其进行建模,因为不经常这样做。
我使用 post_save 信号来保存路径:
def _recurse_for_parent(cat_obj, path=None):
# path at the beginning don't exist and need to be initialized
if not path:
path = []
if cat_obj.parent is not None:
_recurse_for_parent(cat_obj.parent, path)
return path
def save_path(sender, instance, **kwargs):
if instance.parent_id:
instance.children = _recurse_for_parent(instance.parent)
instance.save()
post_save.connect(save_path, sender=Category)
我的问题是我得到了 "maximum recursion depth error" 但我不明白为什么,因为我使用了条件:
cat_obj.parent is not None:
函数中存在多个问题
def _recurse_for_parent(cat_obj, path=None):
# path at the beginning don't exist and need to be initialized
if not path:
path = []
if cat_obj.parent is not None:
_recurse_for_parent(cat_obj.parent, path)
return path
首先请记住 not []
将 return 为真,因此如果您将路径设置为 [],该函数每次都会执行相同的操作。使用 is None
代替
其次,从未使用递归调用的值。
终于想到两个条件都为真时追加什么。
我在 def save_path
中发现错误 我调用 instance.save()
,这将触发 post_save
信号。
因为 post_save
信号调用 save_path
并且 save path
调用 save
触发 post_save
,我进入了一个无限循环。
我通过将我的逻辑移动到 save
方法来解决。
我有一个 Category 模型,其中 ForeignKey 是 self。
class Category(SEO, MetaData):
parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE)
path = ArrayField(models.IntegerField(), blank=True, null=True)
我引入了路径字段,以避免在小部件中进行递归,并对其进行建模,因为不经常这样做。
我使用 post_save 信号来保存路径:
def _recurse_for_parent(cat_obj, path=None):
# path at the beginning don't exist and need to be initialized
if not path:
path = []
if cat_obj.parent is not None:
_recurse_for_parent(cat_obj.parent, path)
return path
def save_path(sender, instance, **kwargs):
if instance.parent_id:
instance.children = _recurse_for_parent(instance.parent)
instance.save()
post_save.connect(save_path, sender=Category)
我的问题是我得到了 "maximum recursion depth error" 但我不明白为什么,因为我使用了条件:
cat_obj.parent is not None:
函数中存在多个问题
def _recurse_for_parent(cat_obj, path=None):
# path at the beginning don't exist and need to be initialized
if not path:
path = []
if cat_obj.parent is not None:
_recurse_for_parent(cat_obj.parent, path)
return path
首先请记住 not []
将 return 为真,因此如果您将路径设置为 [],该函数每次都会执行相同的操作。使用 is None
代替
其次,从未使用递归调用的值。
终于想到两个条件都为真时追加什么。
我在 def save_path
中发现错误 我调用 instance.save()
,这将触发 post_save
信号。
因为 post_save
信号调用 save_path
并且 save path
调用 save
触发 post_save
,我进入了一个无限循环。
我通过将我的逻辑移动到 save
方法来解决。