rsinger86/drf-flex-fields

Expand feature in multi database

Closed this issue · 1 comments

HI,
I have to use drf-flex-field in multi database architecture.
Currently I am looping through all the databases and fetching the result. but when I pass expand it breaks and raise error that Model doesn't exists. because it is selecting default database.

Is there any way to pass the database name to be using when expanding and serialising?

Solved using context manager and setting up the database manually.

THREAD_LOCAL = threading.local()
class InDatabase(object):
    def __init__(self, db_name, *args, **kwargs):
        self.db_name = db_name

    def __enter__(self):
        setattr(THREAD_LOCAL, "DB", self.db_name)
        return self.db_name

    def __exit__(self, exc_type, exc_val, exc_tb):
        setattr(THREAD_LOCAL, "DB", 'default')
for db in databases:
    with InDatabase(db.db_name):
        #No need to use using method
         Model.obejcts.all()
        #will give result from selected database