Search code examples
djangocelerydjango-querysetdjango-celery

Celery won't traverse Django foreign key relationships


I'm running two instances on Heroku:
1. Gunicorn
2. Celeryd

In my email templates I have something to the effect of:

orders.orderitem_set.all

When I render these emails via the web instance (ie. without Celery) I get a list of order items (as expected).

However, when I render these templates with Celery, the list is empty.

Why won't Celery traverse foreign key relationships in templates and how do I know what is in and out of scope?


Solution

  • Most likely the problem is that the django database objects are stale at the moment of execution of the celery tasks.

    This problem was noted by Deni Bertovic in https://denibertovic.com/posts/celery-best-practices/

    You shouldn't pass Database objects (for instance your User model) to a background task because the serialized object might contain stale data. What you want to do is feed the task the User id and have the task ask the database for a fresh User object.