Josh Pearce
Josh Pearce

Reputation: 3455

Using Django's ORM in a Celery Task

How can a Celery task have access to the Django database-abstraction API? Does this need to be coded from scratch using one of the strategies for stand-alone Django ORM usage, or is there a more streamlined, built-in way or common practice?

It seems that nobody is asking this question. However, to me, it's fundamental.

This example implies that it's no big deal, but can someone explain how the session management and ORM scoping works between Celery and Django?

Upvotes: 13

Views: 5195

Answers (2)

Dave Peck
Dave Peck

Reputation: 1352

By default Celery pickles its task parameters. Django model instances can be pickled too.

The catch is that pickling a model instance is like taking a snapshot of it at that time. Unpickling doesn't touch the database.

Whether this is good or bad depends, I suppose, on your needs. I tend to send a primary key into my tasks and re-query for the object in question.

Upvotes: 6

sneeu
sneeu

Reputation: 2652

You probably want to have a look at django-celery.

When doing work as a celery task, you want to pass all of the details to celery, for example to send an email, you’d pass in values for “from”, “to”, “subject”, and “body”.

If you then wanted to notify the user of the action being completed, you’d probably want to have a look at something like the messages framework in Django.

I hope that helps.

Upvotes: 0

Related Questions