[英]2 different references from the same object to two different objects from the same class - DJANGO database
I want to have a match object with two team references.我想与两个团队参考匹配 object。 IE(old json database example):
IE(旧 json 数据库示例):
I would like to easeliy be able to access each team and possibly swap side.我希望能够轻松访问每个团队并可能交换边。 That's why I want to use Django example 2, as then I can reference each team from the Match Object.
这就是我想使用 Django 示例 2 的原因,因为这样我就可以参考比赛 Object 中的每个团队。 But example gives an error about each reference duplicating each other...
但是示例给出了一个关于每个引用相互重复的错误......
{
"dateTime": "",
"matchID":"0fb86bcf-c700-4429-b5a9-558ca9b95a03",
"team1ID":"e372b7f4-008f-4503-beee-1d6756361fea",
"team2ID":"802b4705-d812-4a88-9246-b14bd18938d8",
"format":3,
"division":"Relegation",
"league":leagueRef,
"game":leagueRef,
}
Django example 1: Django 示例 1:
class Match(models.Model):
...
team = models.ManyToManyField(
Team,
on_delete=models.CASCADE,
)
Django example 2: Django 示例 2:
class Match(models.Model):
...
team1 = models.OneToOneField(
Team,
on_delete=models.CASCADE,
)
team2 = models.OneToOneField(
Team,
on_delete=models.CASCADE,
)
When one uses a OneToOneField
(or any other related field) Django automatically makes a reverse accessor on the other side of the relation.当使用
OneToOneField
(或任何其他相关字段)时,Django 会自动在关系的另一侧创建反向访问器。 So in the model team Django will automatically make an attribute with the name match
to access this related object.所以在 model 团队中,Django 会自动做一个名称
match
的属性来访问这个相关的 object。 The problem is you have two of these fields making Django not know what name to use for them.问题是您有两个这样的字段使 Django 不知道为它们使用什么名称。
You can solve this by specifying a related_name
[Django docs] :您可以通过指定
related_name
[Django docs]来解决此问题:
class Match(models.Model):
...
team1 = models.OneToOneField(
Team,
on_delete=models.CASCADE,
related_name='match_1'
)
team2 = models.OneToOneField(
Team,
on_delete=models.CASCADE,
related_name='match_2'
)
Note : By using a
OneToOneField
it means that one team can only have one entry in theMatch
table (once from both sides).注意:使用
OneToOneField
意味着一支球队在Match
表中只能有一个条目(双方各一次)。 So in essence with this a team can only be in 2 matches.因此,从本质上讲,一支球队只能参加 2 场比赛。 Perhaps you want to use a
ForeignKey
[Django docs] instead.也许您想改用
ForeignKey
[Django docs] 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.