bernardopires / django-tenant-schemas

Tenant support for Django using PostgreSQL schemas.
https://django-tenant-schemas.readthedocs.org/en/latest/
MIT License
1.45k stars 424 forks source link

[solved] How to use crontab and django tenants for tasks #636

Closed alisonsandrade closed 4 years ago

alisonsandrade commented 4 years ago

Good evening.

I'm trying to use crontab with django_tenants_schemas, but to no avail. I am using the Kronos library (https://github.com/jgorset/django-kronos) and I have done all the configuration. When trying to include the task the command line is added to the Unix crontab, but it does not execute.

When debugging the code I realized that I am suffering from the django.db.utils.ProgrammingError error, most likely because crontab is trying to execute the tasks directly from the public schema and in this schema it does not have the task tables.

Can anyone indicate a solution? I know that there is a django_tenant_celery library, but as my tasks are quite simple I didn't want to have to use celery.

Thank you very much in advance.

I'm using:

alisonsandrade commented 4 years ago

After several attempts and debugging I finally got it. I will leave the answer registered here so that someone who has the same problem can be helped.

The problem is that manage.py was executing the crontab command taking into account the public schema and as it does not have all the tables it triggers the ProgrammingError error.

The solution was to exclude the public schema from the send_mail function as follows:

@kronos.register('* * * * *')
def send_mail_job():
    for tenant in get_tenant_model().objects.all():
        if tenant.schema_name != 'public':
            with tenant_context(tenant):
                [...]