Django import loop between celery tasks and my models

I use celery with my django project.

In the celery task file, I need to import my models in order to call the model methods. However, I would also like my model to be able to run certain celery tasks.

Now I import my models into celery, but when I try to import celery tasks into my model files, they lead to an import cycle and an import error.

What is the right way to do this?

+8
django celery importerror
source share
4 answers

What I ended up doing is using imports within methods, rather than general imports at the top of the model file. Obviously, I do not need circular imports. My problem was that I imported the model at the top of the celery task file and imported the celery tasks at the top of the model file. It was not really necessary. by cutting off imports I was able to avoid the circular import problem

+8
source share

Celery provides a send_task() method that allows you to send a task by name, thereby eliminating the need to import it - for example:

 # models.py from celery import current_app # no need to import do_stuff from tasks because it will be sent by name current_app.send_task('myapp.tasks.do_stuff', args=(1, 'two'), kwargs={'foo': 'bar'}) 

More details in the documentation .

+2
source share

A common approach to solving these seemingly circular dependency problems is to separate the code that can be imported by both models and tasks. For example, you can specify the model methods that you are talking about. Your models will import this factorized code, as well as tasks.

+1
source share

How not to use tasks.py and just apply task decorators to methods in models.py?

+1
source share

All Articles