在 django 中实现 "teams" 的模型

Implementing a model for "teams" in django

我想在 django 1.8 中实现一个团队功能。 (团队如运动队)

每个用户一次最多可以加入一个团队,因此一个团队可以容纳很多用户。现在我不确定如何定义我的 models.py

我从这个核心开始,但现在我不确定如何建立团队<->用户的连接

from django.db import models

class Team(models.Model):
    name = models.CharField(max_length=64, unique=True)
    description = models.TextField(max_length=1024)
    logo = models.ImageField()

from django.contrib.auth.models import User

class Player(models.Model):
    user = models.OneToOneField(User)
    team = ForeignKey('Team')

我现在是创建第二个 class user_team 还是只是将团队作为用户的外键添加? (如果那是我需要在哪里做的方式?)

谢谢,

我们

// 编辑:我在底部添加了一些代码。这个 Player 模型是否足以定义关系?

按照@aumo 的建议,我通过添加这样的用户配置文件模型解决了这个问题:

from django.contrib.auth.models import User

class Player(models.Model):
    user = models.OneToOneField(User)
    team = models.ForeignKey('Team')

我选择这个解决方案而不是将团队添加为 Teams class 中的 ManyToMany 字段,因为我不确定在开发过程中是否需要向 Player 添加更多字段。

感谢大家的帮助。

对于这个用例,我仍然会建议使用 ManyToMany 字段、中间模型和模型管理器的替代方案。

快速示例结构如下所示:

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


class Team(models.Model):
    name = models.CharField(max_length=64, unique=True)
    description = models.TextField(max_length=1024)
    logo = models.ImageField()
    players = models.ManyToManyField(User, through='Player')


class PlayerManager(models.Manager):
    use_for_related_fields = True

    def add_player(self, user, team):
        # ... your code here ...

    def remove_player(self, user, team):
        # ... your code here ...

    def trasnfer_player(self, user, team):
        # ... your code here ...


class Player(models.Model):
    user = models.ForeignKey(User)
    team = models.ForeignKey(Team)
    other_fields = #...

    objects = PlayerManager()

用法:

Player.objects.add_player(user, team, *other_fields)

然后您将能够获得User相关的Team,例如:

team_with_user = Team.objects.filter(players__name="hello")
user_in_team = User.objects.filter(team__name="world")

注意:我没有测试过代码,如有错误请指正。

我喜欢这种方式的原因是将您的数据库逻辑抽象到应用程序中。所以以后如果需要允许User加入多个团队,你可以改变应用程序逻辑,通过管理器允许它。