garetHollamdaf
garetHollamdaf

Reputation: 379

Adding fields to table dynamically in django

After reading about database designs, i've decided to go with a single table for all users.

I appreciate any advise regarding this subject.

Upvotes: 1

Views: 1010

Answers (1)

corecase
corecase

Reputation: 1298

Since you're using Django, I would recommend reading the Django documentation and/or their getting started tutorials - they have really easy to follow guides on their website. Part 2 of their guide is probably what you're looking for (https://docs.djangoproject.com/en/2.0/intro/tutorial02/), but I would start reading from Part 1 (https://docs.djangoproject.com/en/2.0/intro/tutorial01/) - they're not very lengthy.

Django provides ORM functionality similar to other ORM frameworks. So in order to automatically generate tables, you need to first define what are called "models" in your Django files that directly map to tables in your MySQL database. In your case, you would define a model called "users".

Once you have defined your model, you can use the python CLI "makemigrations" command to automatically generate the related migration file for the users model. Migrations are the intermediary files that help Django create the associated tables in the database.

As for retrieving data from the database (that is specific to each user), you would have to write a set of endpoints in Django that will automatically run the appropriate SQL commands on your database and return the data that was found. For example, you might have an endpoint called getAllUsers that will map to a python (Django) function, which will retrieve all user data from the users table and return it.

The Django documentation explains how to make queries to your database. Check out this page: https://docs.djangoproject.com/en/2.0/topics/db/queries/

Hope this helps you out!

Upvotes: 1

Related Questions