为什么在Django模式的保存期间post_save被提升两次? [英] Why is post_save being raised twice during the save of a Django model?

查看:531
本文介绍了为什么在Django模式的保存期间post_save被提升两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我附加一个方法到我的Django模型的post_save信号。这样我可以在修改模型时清除一些缓存的项目。

I am attaching a method to the post_save signal of my Django model. This way I can clear some cached items whenever the model is modified.

我遇到的问题是当保存模型时,信号被触发两次。它不一定会伤害任何东西(代码将正常出错),但不能正确。

The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error out) but it can't be right.

一个简单的例子,只是将模型打印到控制台(使用dev服务器):

A quick example, just printing the model to the console (using the dev server):

from blog.models import Post
from django.db.models import signals

def purge_cache(sender, **kwargs):
    print 'Purging %s' % sender

signals.post_save.connect(purge_cache, sender=Post)

这是使用稳定的1.1.1版本的Django。

This is using the stable 1.1.1 release of Django.

更新的信息:

根据每个人的意见反馈,我修改了我的问题,因为问题现在发现为什么post_save正在被触发两次。我的猜测是,我的models.py代码被导入两次,post_save被多次连接。

With feedback from everyone's comments, I have modified my question because the issue is now discovering why the post_save is being triggered twice. My guess at the moment is that my models.py code is imported twice and that the post_save is getting connected multiple times.

什么是最好的方式弄清楚为什么要导入/运行两次?

推荐答案

显然,Python对导入模块的方式敏感。在我的情况下,我的博客应用程序中的任何导入代码不是问题,而是INSTALLED_APPS配置的问题,我认为Django会使用它来初始导入。

Apparently, Python is sensitive to the way you import modules. In my case, it wasn't an issue with any of import code inside my blog application but an issue with the INSTALLED_APPS configuration, which I assume is used by Django to do an initial import.

在我的博客应用程序中,我正在使用导入,例如:

Inside my blog application I was using imports such as:

from blog.models import *

我的settings.py配置为:

My settings.py was configured as:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    ...snip...
    'sorl.thumbnail',
    'mysite.blog',
)

添加mysite前缀,因为我最初在部署站点时有导入路径问题。稍后我通过在我的WSGI脚本中添加多个路径来修复此问题(因此它与开发服务器相同)。

The "mysite" prefix was added because I originally had import path issues when deploying the site. Later I fixed this issue (so it acted the same as the development server) by adding multiple paths in my WSGI script.

从设置中删除mysite前缀。 py修复了问题:

Removing the "mysite" prefix from the settings.py fixed the issue:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    ...snip...
    'sorl.thumbnail',
    'blog',
)

这篇关于为什么在Django模式的保存期间post_save被提升两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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