tags:

views:

70

answers:

1

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?

+5  A: 

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).

T. Stone
that's right, but I'd make owner a ManyToMany field, that way same game could be shared by many users
Evgeny
Based on the OP's description of "one table per user" I was assuming there would never be that occurrence. Depending on the application though there certainly could be.
T. Stone