Niladry Kar
Niladry Kar

Reputation: 1203

Django: How to create a signal for deleting a instance of pre_save signal?

I have the following pre_save signal in my models:

@receiver(pre_save, sender=Purchase)
def user_created_purchase_cgst(sender,instance,*args,**kwargs):
    c = Journal.objects.filter(user=instance.user, company=instance.company).count() + 1
    if instance.cgst_alltotal != None and instance.cgst_alltotal != 0:
        Journal.objects.update_or_create(
            user=instance.user,
            company=instance.company,
            by=ledger1.objects.filter(user=instance.user,company=instance.company,name__icontains='CGST').first(),
            to=instance.party_ac,
            defaults={
                'counter' : c,
                'date': instance.date,
                'voucher_id' : instance.id,
                'voucher_type' : "Journal",
                'debit': instance.cgst_alltotal,
                'credit': instance.cgst_alltotal}
            )

I want to create another signal similar to the above that when the sender is deleted then the sender instance will also get deleted.

i.e when a Purchase object is deleted then the corresponding Journal object which is created by the pre_save signal will get deleted.

Any idea anyone how to perform this?

Thank you

Upvotes: 0

Views: 4620

Answers (1)

Stargazer
Stargazer

Reputation: 1530

It will be something like this:

@receiver(pre_delete, sender=Purchase)
def delete_related_journal(sender, instance, **kwargs):
    journal = instance.journal # instance is your Purchase instance that is
    # about to be deleted
    journal.delete()

But be aware, if the Journal purchase Foreign Key is setted to on_delete=models.CASCADE, you don't have to do this at all. So, if CASCADE is not setted, you might want to do it instead using a signal.

class JournalModel(models.Model):
    # Your other fields here
    purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE)

More on pre_delete signals: docs

Upvotes: 3

Related Questions