在django中使用Pre_delete信号

时间:2012-12-13 09:42:04

标签: python django django-models django-signals

在我的应用中,我想跟踪所有被删除的问题。所以我在我的模型文件中创建了一个类(表)。

class Deleted(models.Model):
question = models.IntegerField(null=True, blank=True)#id of question being deleted
user = models.IntegerField(null=True, blank=True)#id of user deleting the question
dt = models.DateTimeField(null=True, blank=True)#time question is deleted

当用户尝试删除问题时,将调用此删除功能:

def delete_questions(request, user, questions):
  for q in questions:
        q.delete()

我怀疑的是我如何制作django的pre_delete信号来填充我创建的新表。

〜新手尝试了大量的任务〜 在此先感谢:)

1 个答案:

答案 0 :(得分:33)

首先定义您要使用的receiver

def log_deleted_question(sender, instance, using, **kwargs):
    d = Deleted()
    d.question = instance.id
    d.dt = datetime.datetime.now() # consider using auto_now=True in your Deleted definition
    # not sure how you'd get the user via a signal, 
    # since it can happen from a number of places (like the command line)
    d.save()

然后定义你的接收器装饰器:

from django.db.models.signals import pre_delete
from django.dispatch import receiver

@receiver(pre_delete, sender=Question, dispatch_uid='question_delete_log')

完全添加:

from django.db.models.signals import pre_delete
from django.dispatch import receiver

@receiver(pre_delete, sender=Question, dispatch_uid='question_delete_signal')
def log_deleted_question(sender, instance, using, **kwargs):
    d = Deleted()
    d.question = instance.id
    d.dt = datetime.datetime.now() 
    d.save()

您可以将此功能放在models.py文件中,因为您知道它会被正确加载和连接。

但问题是,您没有让用户请求删除。由于可以从django api(命令行,shell等)触发删除,因为它没有与之关联的请求。因此,如果将用户与删除一起存储绝对至关重要,您可能希望避免使用信号。