[Solved]-Dynamic database tables in django

13đź‘Ť

âś…

An interesting question, which might be of wider interest.

Creating one table per user is a maintenance nightmare. You should instead define a single table to hold all users’ data, and then use the database’s capabilities to retrieve only those rows pertaining to the user of interest (after checking permissions if necessary, since it is not a good idea to give any user unrestricted access to another user’s data without specific permissions having been set).

Adopting your proposed solution requires that you construct SQL statements containing the relevant user’s table name. Successive queries to the database will mostly be different, and this will slow the work down because every SQL statement has to be “prepared” (the syntax has to be checked, the names of table and columns has to be verified, the requesting user’s permission to access the named resources has to be authorized, and so on).

By using a single table (model) the same queries can be used repeatedly, with parameters used to vary specific data values (in this case the name of the user whose data is being sought). Your database work will move along faster, you will only need a single model to describe all users’ data, and database management will not be a nightmare.

A further advantage is that Django (which you appear to be using) has an extensive user-based permission model, and can easily be used to authenticate user login (once you know how). These advantages are so compelling I hope you will recant from your heresy and decide you can get away with a single table (and, if you planning to use standard Django logins, a relationship with the User model that comes as a central part of any Django project).

Please feel free to ask more questions as you proceed. It seems you are new to database work, and so I have tried to present an appropriate level of detail. There are many pitfalls such as this if you cannot access knowledgable advice. People on SO will help you.

👤holdenweb

4đź‘Ť

This page shows how to create a model and install table to database on the fly. So, you could use type('table_with_username', (models.Model,), attrs) to create a model and use django.core.management to install it to the database.

👤defool

Leave a comment