首页 > 解决方案 > Django:模型设计建议

问题描述

我需要帮助为我的简单 Django 应用程序创建模型。

该应用程序的目的是让用户(裁判)注册比赛,然后管理员将从注册给定比赛的列表中选择 2 个用户(裁判)。现在我的 Matches 模型如下所示:

class Match(models.Model):

    match_number = models.CharField(
        max_length=10
    )
    home_team = models.ForeignKey(
        Team,
        on_delete=models.SET_NULL,
        null=True,
        related_name='home_team'
    )
    away_team = models.ForeignKey(
        Team,
        on_delete=models.SET_NULL,
        null=True,
        related_name='away_team'
    )
    match_category = models.ForeignKey(
        MatchCategory,
        on_delete=models.SET_NULL,
        null=True
    )
    date_time = models.DateTimeField(
        default=timezone.now
    )
    notes = models.TextField(
        max_length=1000,
        blank=True
    )

我想做的是创建一个名为 MatchRegister 的新模型,我将在其中保存 match_id 和 user_id,如下所示:

class MatchRegister(models.Model):
    match_id = models.ForeignKey(
        Match
    )
    user_id = models.ForeignKey(
        Users
    )

并且管理员将拥有给定匹配的注册用户列表,他将从中选择两个,所以我想像这样修改我的匹配模型(添加两个新字段):

class Match(models.Model):

    match_number = models.CharField(
        max_length=10
    )
    home_team = models.ForeignKey(
        Team,
        on_delete=models.SET_NULL,
        null=True,
        related_name='home_team'
    )
    away_team = models.ForeignKey(
        Team,
        on_delete=models.SET_NULL,
        null=True,
        related_name='away_team'
    )
    match_category = models.ForeignKey(
        MatchCategory,
        on_delete=models.SET_NULL,
        null=True
    )
    date_time = models.DateTimeField(
        default=timezone.now
    )
    notes = models.TextField(
        max_length=1000,
        blank=True
    )
    ref_a = models.ForeignKey(
        Users,
        on_delete=models.SET_NULL,
        null=True,
        related_name='ref_a'
    )

    ref_b = models.ForeignKey(
        Users,
        on_delete=models.SET_NULL,
        null=True,
        related_name='ref_b'
    )

这是我的解决方案,但我不知道它是否以正确的方式完成,所以我想向您寻求帮助。

标签: pythondjango

解决方案


如果您确定比赛只会有两个裁判,那么您的建议就可以了。但是,如果将来有机会更改数字(只有一个,或者可能是三个),另一种方法是在中间表中添加一个标志:

class MatchRegister(models.Model):
    match_id = models.ForeignKey(Match)
    user_id = models.ForeignKey(Users)
    chosen = models.BooleanField(default=False)

您需要业务逻辑来将“选择”引用的数量限制为您预期的数量。此选项可以轻松增加或减少 ref 的数量,而无需添加或删除列(只需更改业务逻辑)。


推荐阅读