I have a model Entry
Now whenever Entry
is created for any date. Then before saving I need to make check and add more entries, for example e.g.
Entry 1 - red
Now suppose if any entry.color = red
Then I also need to make two more entries like
Entry 2 - red2
Entry 3 - red3
Now I have put this in pre_save signal
@receiver(pre_save, sender=Entry)
def new_entries(sender, instance, *args, **kwargs):
pass
Now my problem is this ends in infinite recursion as those new entries which I want to save also send pre_save signal and this loop never finishes.
Where do put this logic so that recursion does not occur?
I would solve it with an additional argument to save, as opposed to attaching to 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
You want to make sure you call super(Entry,self).save(**kwargs)
before you actually construct the children, otherwise you will clutter the database with models when super() raises an IntegrityError
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments