Django OneToOneField 结构

Django OneToOneField Structure

我一直在研究和查看所有文档,但我仍然有点困惑,我想可能是因为有多种方法可以使用 OnToOneField。

我有 4 个模型,Pregame、Ingame、Postgame 和 Game。我希望 'Game' 包含其他三个模型。

目前看起来像这样...

    class Pregame(models.Model):
        game_id = models.CharField(max_length=10)
        other fields...

        def __str__(self):
            return str(self.game_id)

    class Ingame(models.Model):
        game_id = models.CharField(max_length=10)
        other fields...

        def __str__(self):
            return str(self.game_id)

    class Postgame(models.Model):
        game_id = models.CharField(max_length=10)
        other fields...

        def __str__(self):
            return str(self.game_id)

    class Game(models.Model):
        game_id = models.CharField(max_length=10)
        pregame = models.OneToOneField(
            Pregame, on_delete=models.CASCADE, null=True)
        ingame = models.OneToOneField(
            Ingame, on_delete=models.CASCADE, null=True)
        postgame = models.OneToOneField(
            Postgame, on_delete=models.CASCADE, null=True)

        def __str__(self):
            return str(self.game_id)

我用的是OnToOne,因为每个Game只有一个Pregame,Ingame和Postgame,其他三个模型只属于一个Game。

我有几个问题很困惑。

如果其他模型对象之一尚不存在,我能否拥有一个 Game 对象?就像如果有 Pregame 但没有 Ingame 或 Postgame,Game 是否仍然存在,只有 Pregame 在里面?我看过几个视频,他们做了 default='{}',那是我应该做的吗?

每个模型都有 game_id,这就是我将它们全部连接到 'Game' 对象中的方式。是否有像 game_id=game_id 这样的 OneToOneField 选项,所以 'Game' 模型会自动 link 所有模型在一起,还是我仍然需要分开做?

感谢您的帮助和知识。

首先,您不必在*游戏实体上设置game_id。您可以只添加 related_name:

class Game(models.Model):
    game_id = models.CharField(max_length=10)
    pregame = models.OneToOneField(
        Pregame, on_delete=models.CASCADE, null=True, related_name="game")
    ingame = models.OneToOneField(
        Ingame, on_delete=models.CASCADE, null=True, related_name="game")
    postgame = models.OneToOneField(
        Postgame, on_delete=models.CASCADE, null=True, related_name="game")

class Pregame(models.Model):
    other fields...

    def __str__(self):
        return str(self.game_id)

Will I be able to have a Game object if one of the other model objects doesn't exist yet? Like if there is a Pregame but no Ingame or Postgame, will Game still exist with just Pregame inside of it? I seen a couple videos where they did a default='{}', is that what I should be doing?

是的,即使没有*游戏,Game 对象也可以存在,正如您添加的 null=True。当您的模型不接受 null/empty 值时,您应该使用默认值。

Each model has game_id and that is how I am connecting them all together into the'Game' object. Is there a OneToOneField option like game_id=game_id so the 'Game' model will automatically link all the models together or would I still have to do that separate?

创建此类模型后,您可以通过 Game 实体进行访问。例如从 pregamepostgame:

postgame = pregame.game.postgame