保存模型后在Django中调用函数 [英] Calling a function in Django after saving a model

查看:110
本文介绍了保存模型后在Django中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:我正在写博客。该博客通过Django模型将有关文章的信息存储在数据库中。我在所说的模型中有一个FileField,它带有与此文件一起的所有资产的存档。我通过管理站点添加文章。

Context: I'm making a blog. This blog stores information on articles in a database via a Django model. I have a FileField in said model that takes an archive of all the assets that go with this file. I add articles through the admin site.

我想调用一个函数,在将对象保存到模型后立即解压缩该文件。我应该在哪里编写此函数?

I want to call a function that unpacks this file immediately after the the object is saved to the model. Where would I write this function?

推荐答案

您可以使用Django中包含的信号分配器。

You can use signal dispatcher included in Django.

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

from myapp.models import Blog

@receiver(post_save, sender=Blog)
def my_handler(sender, **kwargs):
    print('post save callback')

请参见 https://docs.djangoproject.com/en/stable/ref/signals/#post-save 了解更多信息。

这篇关于保存模型后在Django中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆