can't import django model into celery task

天大地大妈咪最大 提交于 2019-12-07 03:40:00

问题


i have the following task:

from __future__ import absolute_import

from myproject.celery import app

from myapp.models import Entity


@app.task
def add(entity_id):
    entity = Entity.objects.get(pk=entity_id)
    return entity.name

I get the following error:

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

If I take out the entity import every thing is fine and no error occurs. When add back :

from myapp.models import Entity

the error returns.

from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.core.mail import EmailMultiAlternatives
from django.template import Context, loader
from django.utils.html import strip_tags

class Entity(models.Model):
    area = models.ForeignKey(Area)
    name = models.CharField(max_length=255)
    type = models.CharField(max_length=255)
    status = models.IntegerField(choices=STATUS_TYPES, default=0)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)


    def __unicode__(self):
        return self.name

How do I import a django model into a celery task?


回答1:


My celery file needed to have:

from __future__ import absolute_import

import os

from celery import Celery


# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

from django.conf import settings  # noqa

Thanks for helping me get to that conclusion @mtndesign



来源:https://stackoverflow.com/questions/36755583/cant-import-django-model-into-celery-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!