Django:如何创建一个删除pre_save信号实例的信号?

问题描述 投票:0回答:1

我的模型中有以下pre_save信号:

@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}
            )

我想创建另一个类似于上面的信号,当发送者被删除时,发送者实例也将被删除。

即当删除Purchase对象时,将删除由pre_save信号创建的相应Journal对象。

任何人都知道如何执行此操作?

谢谢

django django-signals
1个回答
2
投票

它将是这样的:

@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()

但请注意,如果日记本购买外键被设置为on_delete=models.CASCADE,您根本不需要这样做。因此,如果未设置CASCADE,您可能希望使用信号来执行此操作。

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

更多关于pre_delete信号:docs

© www.soinside.com 2019 - 2024. All rights reserved.