我的模型中有以下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
对象将被删除。
有人知道如何执行此操作吗?
谢谢
答案 0 :(得分: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