Home > other >  An event for when the last object is saved via Django formset
An event for when the last object is saved via Django formset

Time:09-06

I have a signal that listens to a model whose relation to another model is like this

class Model1(models.Model):
    field1 = models.CharField(max_length=4)

class ChildToModel1(models.Model):
    model_1 = models.ForeinKey(Model1, related_name='model_1', on_delete=models.CASCADE)

Now I have an inlineformset_factory for ChildToModel1 according to django calling save for ChildToModel1 inlineformset_factory will save multiple instance of ChildToModel1 like it's a forloop. If I have, for example; 3 formset is there a way to check the total of the objects after total save and not on each save, I am accessing these on the model post_save signal.

printing ChildToModel1 on post_save signal returns something like this

<QuerySet [obj]>
<QuerySet [obj][obj]>
<QuerySet [obj][obj][obj]>

What I really want is:

<QuerySet [obj][obj][obj]>

CodePudding user response:

You can trigger other signal manually at the end.

First define new signal: https://docs.djangoproject.com/en/4.0/topics/signals/#defining-signals

import django.dispatch

post_save_after_last = django.dispatch.Signal()

and then import it and trigger it

from somewhere import post_save_after_last

last_instance = ChildToModel1(field='qwerty')
post_save_after_last.send(sender=ChildToModel1, instance=instance)

You can read more here: https://docs.djangoproject.com/en/4.0/topics/signals/#sending-signals

  • Related