我有一个模型Entry
现在每当为任何日期创建Entry 时。然后在保存之前我需要进行检查并添加更多条目,例如
条目 1 - 红色
现在假设如果有 entry.color = red 那么我还需要再创建两个条目,例如
Entry 2 - red2
Entry 3 - red3
现在我把它放在 pre_save 信号中
@receiver(pre_save, sender=Entry)
def new_entries(sender, instance, *args, **kwargs):
pass
现在我的问题是以无限递归结束,因为我要保存的那些新条目也会发送 pre_save 信号,并且此循环永远不会结束。
将此逻辑放在哪里才能避免递归?
请您参考如下方法:
我会用一个额外的参数来解决它,而不是附加到 pre_save:
import django.db.models
class Entry(models.Model):
color=models.CharField(max_length="50")
def save(self,create_children=True,**kwargs):
if create_children and not self.pk:
result = super(Entry,self).save(**kwargs)
Entry(color=self.color).save(create_children=False)
Entry(color=self.color).save(create_children=False)
else:
result = super(Entry,self).save(**kwargs)
return result
你要确保在实际构造子项之前调用 super(Entry,self).save(**kwargs),否则当 super() 引发时,你会用模型弄乱数据库一个 IntegrityError
