dynamically set database based on request in django

后端 未结 2 1822
执念已碎
执念已碎 2020-12-07 19:36

I am writing a multi-tenant application with python-django.

I want to set database connection based on each request.I thought i could write a middleware where we set

2条回答
  •  广开言路
    2020-12-07 19:54

    Maybe you can use:

    https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database-for-a-queryset

    Entity.objects.using('context1').all()
    Entity.objects.using('context2').all()
    

    To select/use a database depending on the request. You can define multiple DBs in the configurartion:

    DATABASES = {
        'context1': {
            'NAME': 'context1',
            'ENGINE': 'db.engine.to.use',
            'USER': 'xxx',
            'PASSWORD': 'xxx'
        },
        'context2': {
            'NAME': 'context2',
            'ENGINE': 'db.engine.to.use',
            'USER': 'xxx',
            'PASSWORD': 'xxx'
        }
    }
    

提交回复
热议问题