我有一个根据子域更改数据库模式的中间件:
def tenant_schema_from_request(request):
hostname = hostname_from_request(request)
tenants_map = get_tenants_map()
return tenants_map.get(hostname)
def set_tenant_schema_for_request(request):
schema = tenant_schema_from_request(request)
with connection.cursor() as cursor:
cursor.execute("SET search_path to {}".format(schema))
class TenantMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
set_tenant_schema_for_request(request)
response = self.get_response(request)
return response
但是如何在芹菜任务中更改数据库架构?
tasks.py
@shared_task
def send_notification_task(user_id):
user = User.objects.get(pk=user_id)
...
我想你正在寻找.using
Author.objects.using('default').all()
希望这有帮助!
老问题,但我遇到了完全相同的问题并找到了解决方案。共享它,以防其他人需要它。
在任务运行之前,应使用芹菜task_prerun
信号切换活动架构。
下面是在任务运行之前将当前架构切换到公共架构的示例。
from celery.signals import task_prerun
from django.db import connection
# ensure the task always runs on the public schema
@task_prerun.connect(sender=send_notification_task)
def activate_public_schema(sender, **kwargs):
connection.schema_name = 'public'
@shared_task
def send_notification_task(user_id):
user = User.objects.get(pk=user_id)
...