Django:如何创建用于删除 pre_save 信号实例的信号?
Django: How to create a signal for deleting a instance of pre_save signal?
我的模型中有以下 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
对象将被删除。
知道如何执行此操作吗?
谢谢
它将是这样的:
@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()
但请注意,如果将 Journal purchase Foreign Key 设置为 on_delete=models.CASCADE
,则根本不必执行此操作。因此,如果未设置 CASCADE,您可能想要使用信号来代替。
class JournalModel(models.Model):
# Your other fields here
purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE)
更多关于 pre_delete
信号的信息:docs
我的模型中有以下 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
对象将被删除。
知道如何执行此操作吗?
谢谢
它将是这样的:
@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()
但请注意,如果将 Journal purchase Foreign Key 设置为 on_delete=models.CASCADE
,则根本不必执行此操作。因此,如果未设置 CASCADE,您可能想要使用信号来代替。
class JournalModel(models.Model):
# Your other fields here
purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE)
更多关于 pre_delete
信号的信息:docs