执行django admin action作为芹菜任务

时间:2015-05-13 12:56:49

标签: django django-admin rabbitmq celery django-admin-actions

正常功能可以作为django管理员操作执行。我想将数据导出为csv文件。由于数据的大小,我试图将其作为芹菜任务执行。但是模型,请求,查询集等的对象不能传递给任务。 有没有办法像芹菜任务一样执行管理操作。

1 个答案:

答案 0 :(得分:1)

从芹菜任务或任何地方(例如管理命令)执行管理操作:

from celery import shared_task
from django.contrib import admin
from django.test.client import RequestFactory
from django.contrib.auth.models import User

@shared_task
def my_task(pk_of_model):
    '''
    Task executes a delete_selected admin action.
    '''

    # the queryset is the set of objects selected from the change list
    queryset = MyModel.objects.filter(pk=pk_of_model)

    # we use the django request factory to create a bogus request
    rf = RequestFactory()

    # the post data must reflect as if a user selected the action
    # below we use a 'delete' action and specify post:'post' to
    # simulate the user confirmed the delete

    request = rf.post(
        '/admin/app/model',   # url of the admin change list
        {
            '_selected_action': [m.pk for m in queryset],
            'action': 'delete_selected',
            'post': 'post', 
        }
    )

    # the request factory does not use any middlewares so we add our
    # system user - some admin user all the tasks and commands run as.
    request.user = User.objects.get(username='SYSTEM') # must exist

    # the admin site registry holds all the ModelAdmin
    # instances where our actions are declared
    admin.site._registry[MyModel].delete_selected(request, queryset)

上面的示例将失败,因为delete_selected操作依赖于messages中间件,而请求工厂不使用任何中间件。可以将最终执行行包装在try: ... except MessageFailure: pass中,但很可能您将执行自己的自定义操作,您可以检查是否已启用消息中间件。