让loaddata忽略或禁用post_save信号 [英] Have loaddata ignore or disable post_save signals

查看:71
本文介绍了让loaddata忽略或禁用post_save信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您要为已创建的应用程序的重大更改设置测试环境,并希望确保系统中现有的数据可以轻松加载到新系统中。

Let's say that you want to setup a test environment for major changes to an application that you have created, and you want to make sure that those data existing in your system will easily load into the new system.

Django提供了用于导出和加载数据的命令行工具。通过 dumpdata loaddata

Django provides command line facilities for exporting and loading data. Via dumpdata and loaddata

python manage.py dumpdata app.Model > Model.json
python manage.py loaddata Model.json

该文档可以识别(尽管


处理夹具文件时,数据按原样保存到数据库中。不调用模型定义的保存方法和pre_save信号。 (

是否有一种方法可以在 loaddata <期间禁用 post_save 信号调用/ code>过程?

Is there a way to disable post_save signal calls during the loaddata process?

可能相关:

  • How do I prevent fixtures from conflicting with django post_save signal code?
  • https://code.djangoproject.com/ticket/8399

推荐答案

一种实现此目的的方法是添加一个装饰器,以寻找信号分派给接收器函数时的原始关键字参数。

One way to achieve this is to add a decorator that looks for the raw keyword argument when the signal is dispatched to your receiver function. This has worked well for me on Django 1.4.3, I haven't tested it on 1.5 but it should still work.

from functools import wraps
def disable_for_loaddata(signal_handler):
    """
    Decorator that turns off signal handlers when loading fixture data.
    """

    @wraps(signal_handler)
    def wrapper(*args, **kwargs):
        if kwargs.get('raw'):
            return
        signal_handler(*args, **kwargs)
    return wrapper

然后:

@disable_for_loaddata
def your_fun(**kwargs):
    ## stuff that won't happen if the signal is initiated by loaddata process

每个文档的raw关键字为:如果模型的保存方式与显示的完全相同(即,加载模型时夹具)。

Per the docs, the raw keyword is: True if the model is saved exactly as presented (i.e. when loading a fixture).

这篇关于让loaddata忽略或禁用post_save信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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