How to use PostgreSQL schemas creation in Django (incl. passing arguments form view to model)?

Viewed 141

I've been searching all day and given up. Django does not have proper support for Postgres schemas, hence the question.

Problem:

I want each user in my app to have their own database schema with a unique name (created when signing up). The tables in each schema are identical to every those in every other schema but obviously the data is different (I want users to have their data isolated from each other). I need to create new DB schemas dynamically, migrate existing models to them dynamically AND retrieve data from the tables using models. This is for an API not a template.

Sub-problems:

  1. Creating new Postgres DB schema dynamically
  2. Retrieving data from tables (with dynamic names) inside DB schema using models [assuming that the name is passed as an argument to a view]

Thus far I've only been able migrate models to empty schemas I manually create (i.e. name is known) using the code below Inside the model:

Meta:
     db_table='schema_name\.\.model_name'</pre>

And during runtime:

from django.core.management import call_command
call_command('makemigrations')
call_command('migrate')

Questions

Sub-problem (1): Is it best to create a Postgress procedure/function and then to call it from inside django? Can I just create a new empty schema in this procedure and copy an existing set of tables that is already set up? Is it possible to create new schemas within django?

Sub-problem (2): Is there any reliable way to pass arguments from a view to a model to set the variable db_table prior to the model manipulating the data? I've considered writing a function-based view that passes key-word arguments to set this variable within the model's special function __init__(). This is however, a very tedious process if I have to apply it to each model. I was wondering if there's a class-based alternative for this method?

List of other solutions that aren't suitable:

  • Using a DBRouter - this only works if you have a known set of databases pre-registered in settings.py. I'm obviously creating such "databases" (i.e. schemas) dynamically

I'm sure this question will help many people in the future, many thanks for your help in advance.

0 Answers
Related