gpt4 book ai didi

python - 在 Django 中使用 Pre_delete 信号

转载 作者:太空狗 更新时间:2023-10-29 17:52:57 25 4
gpt4 key购买 nike

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

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

~新手尝试繁重的任务~提前致谢:)

最佳答案

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

关于python - 在 Django 中使用 Pre_delete 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13857007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com