【问题标题】:Django, have model to be related to many instances of itselfDjango,有模型与自身的许多实例相关
【发布时间】:2021-03-20 19:05:50
【问题描述】:

我有一个模型:

class Industry(models.Model):
    name = models.CharField(max_length=60, unique=True, null=False, blank=False)

我希望它有一个 sub_industries 字段来保存其所有子行业,这些子行业应该是 Industry 模型的实例。

我不能成为ManyToMany,因为每个行业只有一个父行业。

【问题讨论】:

  • 你可以使用一对一比
  • 您也不想拥有 Onetomany 关系吗?因为似乎外键可以为您解决这个问题,因为 sub_industries 包含一个行业的所有子
  • ForeignKey 应该为您完成这项工作。
  • 感谢 cmets 伙计们! ForeignKey 好像在干活。

标签: python sql django django-models foreign-keys


【解决方案1】:

您可以使用以下方法将ForeignKey 添加到自身:

class Industry(models.Model):
    name = models.CharField(max_length=60, unique=True)
    parent_industry = models.ForeignKey(
        'self',
        null=True,
        related_name='sub_industries'
    )

你可以用NULL/None来表示一个行业没有父级。

【讨论】:

  • 到目前为止,这是我的解决方案。现在,我可以像访问其他任何领域一样在 Industry 中访问 sub_industries,对吧?
  • @Karol:对于给定的myindustry,您可以使用myindustry.sub_industries.all() 访问它。
猜你喜欢
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-25
  • 2022-01-07
  • 2014-12-14
  • 1970-01-01
相关资源
最近更新 更多