首页 > 解决方案 > 我是否应该在两个相关模型中重复字段

问题描述

我有两个相关的模型。具有以下字段的第一个模型夹具

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 中是否正确?

标签: djangodjango-models

解决方案


在 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

推荐阅读