[Django]-Django model object as parameter for celery task raises EncodeError – 'object of type someModelName is not JSON serializable'

6πŸ‘

βœ…

Add this lines to settings.py

# Project/settings.py
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

Then instead of passing object, send JSON with id/pk if you’re using a model instance call the task like this..

test.delay({'pk': 1})

Django model instance is not available in celery environment, as it runs in a different process

How you can get the model instance inside task then? Well, you can do something like below –

def import_django_instance():
    """
    Makes django environment available 
    to tasks!!
    """
    import django
    import os
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings')
    django.setup()


# task
@shared_task(name="simple_task")
def simple_task(data):
    import_django_instance()
    from app.models import AppModel

    pk = data.get('pk')
    instance = AppModel.objects.get(pk=pk)
    # your operation
πŸ‘€Raihan Kabir

Leave a comment