django - 我是否应该在两个相关模型中重复字段
问题描述
我有两个相关的模型。具有以下字段的第一个模型夹具
class Fixture(models.Model):
fixture_id = models.IntegerField()
team_id = models.ForeignKey("Team")
team_logo = models.ForeignKey("Team")
和具有以下领域的第二个模型团队
class Team(models.Model):
team_id = models.IntegerField()
team_logo = models.URLField()
在上面的代码中,夹具模型中的一些字段,如 team_id 和 team_logo 是 Team 模型中重复的 team_id 和 team_logo 字段。如果夹具模型中的 team_id 需要我与团队模型建立关系,但 team_logo 什么都不做,只是重复。这是我的问题,根据第一个数据库规范化规则“每条记录应该是唯一的”存储在夹具模型 team_logo 中是否正确?
解决方案
在 Django 中,默认情况下每个模型都有一个基于整数的id
字段(您可以通过 引用它pk
)。此外,鉴于您的数据以及您使用的是关系数据库这一事实,您不需要将数据从一个模型复制到另一个模型。例如,这就足够了:
class Fixture(models.Model):
team = models.ForeignKey("Team")
description = models.TextField()
class Team(models.Model):
name = models.CharField(max_length=30)
logo = models.URLField()
这让您可以:
# assume this is some uploaded file:
logo_image_file = ...
team_lfc = Team.objects.create(name='Liverpool FC', logo=logo_image_file)
fixture1 = Fixture.objects.create(team=team_lfc, description='Manchester City in August')
# access the 'auto' id/pk:
# these two are the same
fixture1.pk
fixture1.id
# these two are the same
team_lfc.pk
team_lfc.id
# access foreign key object:
fixture1.team
# access foreign key id:
fixture1.team_id
fixture1.team.id
fixture1.team.pk
# access the team's logo from a fixture instance:
fixture1.team.logo
推荐阅读
- java - 我们可以在 App 模块中使用库模块的资源吗?
- android - 使用 Mp 图表为组条中的每个单独条设置名称
- spacy - 在 spacy 实体链接中显示来自 kb id 的实体描述
- r - 如何在 Mac 上增加 R 的内存限制?
- python - 在递归下传递Python函数内部变量的值
- python - TypeError:传递 PeriodDtype 数据无效。改用`data.to_timestamp()`
- scala - 如何使用主类选择对话框?
- google-apps-script - 从不是由 Google Apps 脚本创建的文件中获取元数据
- c++ - 如何从派生类的构造函数中正确访问这个基类变量?
- android - Android camera2 ImageReader导致冻结