13

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

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 信号来填充我创建的新表。

〜新手尝试繁重的任务〜在此先感谢:)

4

1 回答 1

41

您首先定义要使用的接收器:

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 等)触发删除,它没有与之关联的请求。出于这个原因,如果将用户与删除一起存储绝对至关重要,那么您可能希望避免使用信号。

于 2012-12-13T10:41:11.240 回答