python - 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'
)
这是我的解决方案,但我不知道它是否以正确的方式完成,所以我想向您寻求帮助。
解决方案
如果您确定比赛只会有两个裁判,那么您的建议就可以了。但是,如果将来有机会更改数字(只有一个,或者可能是三个),另一种方法是在中间表中添加一个标志:
class MatchRegister(models.Model):
match_id = models.ForeignKey(Match)
user_id = models.ForeignKey(Users)
chosen = models.BooleanField(default=False)
您需要业务逻辑来将“选择”引用的数量限制为您预期的数量。此选项可以轻松增加或减少 ref 的数量,而无需添加或删除列(只需更改业务逻辑)。
推荐阅读
- bolt-cms - 是否可以在 Bolt CMS 4 中构建模块化页面?类似于 GravCMS 模块化页面或 SuluCMS 内容块
- c# - 试图对硬盘进行压力测试,但 Windows 在读取期间显示没有硬盘使用情况
- html - 去掉 div 之间的空格
- ruby - ruby gem`grpc`没有连接到通过`grpcurl`命令行连接的服务
- javascript - 角度的导入和导出
- python - 在 pandas groupby 上使用 map 或 applymap
- actions-on-google - CameraStream 特征不接受 PIN 验证
- google-maps - 为什么我的自定义 Google 地图不再起作用?
- javascript - 当前 div 的 LocalStorage?
- ssis - ssis 中 ODBC 连接的更新表