【发布时间】:2018-03-20 21:53:38
【问题描述】:
我目前在 django-cms 工作,并在我的几个模型中使用PlaceholderField。因此,我想概括这个过程以避免必须覆盖每个模型的删除,并为每种类型的对象添加一个专门的管理器来处理删除。
一点背景故事:
在稍微改进了我的应用程序的设计并使用(老实说令人印象深刻的)PlaceholderFields 之后,我注意到如果我删除了包含这些字段之一的模型,它会在删除后留下它的插件/占位符产生它的模型实例。这让我很惊讶,所以我联系了他们,据 django-cms 的开发团队说:
根据设计,django CMS
PlaceholderField不会为您处理插件的删除。 如果您想在删除引用它的对象时清除占位符内容并删除占位符本身,您可以通过在占位符实例上调用clear()方法然后调用delete()方法来实现
既然这预计会在删除模型之前发生,我的第一个想法是使用 django 提供的pre_delete 信号。所以我设置了以下内容:
我的问题
models.py
class SimplifiedCase(models.Model):
#... fields/methods ...
my_placeholder_instance= PlaceholderField('reading_content') # ****** the placeholder
#define local method for clearing placeholderfields for this object
def cleanup_placeholders(self):
# remove any child plugins of this placeholder
self.my_placeholder_instance.clear()
# remove the placeholder itself
self.my_placeholder_instance.delete()
# link the reciever to the section
signals.pre_delete.connect(clear_placeholderfields, sender=SimplifiedCase)
信号.py
# create a generalized reciever
#(expecting multiple models to contain placeholders so generalizing the process)
def clear_placeholderfields(sender, instance, **kwargs):
instance.cleanup_placeholders() # calls the newly defined cleanup method in the model
我希望这可以正常工作,但是在从 pre_delete 接收器调用的方法中调用 [placeholder].delete() 方法时,我得到了一些奇怪的行为。
由于某种原因,在我的cleanup_placeholders 方法中调用占位符的delete() 方法时,它会再次触发父级的pre_delete 方法。导致递归循环
我对使用 django/django-cms 比较陌生,所以我可能忽略了某些东西或从根本上误解了导致此循环的原因,但是有没有办法使用 @987654334 来实现我在这里尝试做的事情@信号?还是我做得不好?
任何建议将不胜感激。
【问题讨论】:
标签: python django django-cms django-signals