Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create one Model (table) for each user on django?

Tags:

django

I have a Model, and want every User of the system has a table reserved for himself, respecting this Model.

To make it clear:

Imagine the Model "Games". I do not want that there is only one table "games", but there is: foo_games, bar_games (foo / bar are users of the system)

How to do this ?


edit:

why ?

Imagine I have 1000 users, and each User has 100 games.

Do you think you have a table with 1000 * 100 items is better than having 1000 tables with 100 items each?

like image 532
Fabricio Lopes Avatar asked Nov 19 '09 17:11

Fabricio Lopes


1 Answers

The way this is typically handled in with the Django ORM is by linking the two models together (tables) with a Foreign Key. You can then get just the records that apply to a user by using the .filter() method. In this way it will seem like each user has their own table. For example...

from django.contrib.auth.models import User
from django.db import models

class Game(models.Model):
    name = models.CharField(max_length=50)
    owner = models.ForeignKey(User)

The ForeignKey field here provides a "link" that relates 1 Game record to a specific User.

When you want to retrieve the Games that apply just to 1 user, you can do so like this:

# Select whichever user you want to (any of these work)
user = User.objects.get(username='admin')
user = User.objects.get(id=64)
user = request.user

# Then filter by that user
user_games = Game.objects.filter(owner=user)

Edit --

To answer your question about more rows vs. more tables: Relational database servers are optimized to have a huge row capacity within a single table. With your example query, 1000 * 100 is only 100,000 records, which is probably only 0.01% of what a table can theoretically hold (server memory and storage aside).

like image 168
T. Stone Avatar answered Oct 08 '22 03:10

T. Stone