如何在Django上为每个用户创建一个模型(表)? [英] How to create one Model (table) for each user on django?

查看:97
本文介绍了如何在Django上为每个用户创建一个模型(表)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,并且希望系统的每个用户都有一个供他使用的表,并尊重这个模型。

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

要明确一点:

想象一下模型游戏。
我不希望只有一个表游戏,但是有:
foo_games,bar_games(foo / bar是系统的用户)

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)

如何执行此操作?

编辑:

为什么?

想象我有1000个用户,每个用户有100个游戏。

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

您有一个包含1000 * 100项的表比拥有1000个具有100项的表好吗?

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

推荐答案

通常这种方式使用Django ORM处理是通过使用外键将两个模型(表)链接在一起。然后,您可以使用.filter()方法获取仅适用于用户的记录。这样,似乎每个用户都有自己的表。例如...

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)

此处的ForeignKey字段提供了一个将1个游戏记录与特定用户相关联的链接。

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

当您要检索仅适用于1个用户的游戏时,可以这样操作:

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)

编辑-

回答关于更多行还是更多表的问题:关系数据库服务器经过优化,可在单个表中具有巨大的行容量。对于您的示例查询,1000 * 100仅是100,000条记录,这可能仅占表理论上可以容纳的记录的0.01%(预留服务器内存和存储空间)。

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

这篇关于如何在Django上为每个用户创建一个模型(表)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆