【问题标题】:Is it possible to have a model reference many other models depending on the situation in django?根据 django 的情况,是否可以让模型引用许多其他模型?
【发布时间】:2021-04-19 19:14:49
【问题描述】:

老实说,我什至不知道如何表达我的问题,但我认为举个例子可能会有所帮助。

我恭敬地用自己的模型为三个应用程序疯狂。应用 1、应用 2、应用 3。我想创建一个新的应用程序(报告),它将报告我的每个其他应用程序(App1、App2、App3)。根据我目前的知识,我的报告 models.py 中有以下内容

class Reports(models.Model):
    name = models.CharField(max_length=150, blank=True)

    app1_reported = models.ForeignKey(
        App1, on_delete=models.CASCADE, related_name='reported_app1', blank=True)

    app2_reported = models.ForeignKey(
        App2, on_delete=models.CASCADE, related_name='reported_app2', blank=True)

    app3_reported = models.ForeignKey(
        App3, on_delete=models.CASCADE, related_name='reported_app3', blank=True)

我有什么方法可以在我的报告模型中创建一个可以引用 App1、App2 或 App3 的引用?类似:

class Reports(models.Model):
    name = models.CharField(max_length=150, blank=True)

    reported = models.ForeignKey(
        App1 or App2 or App3, on_delete=models.CASCADE, related_name='reported_app_is', blank=True)

我的应用在第一次实现时运行良好我只是想知道是否有更好的方法。另外请让我知道这是否有意义,我正在努力寻找正确的措辞。

【问题讨论】:

  • 如果我理解,你有三个应用程序,每个应用程序都有一个同名的模型?
  • @BriseBalloches 是的,先生,这是正确的。
  • 这可能对你有帮助stackoverflow.com/a/881874/4151233
  • 谢谢@Marco,我检查了链接并设法让它在一定程度上工作。我还检查了帖子中建议的文档以及下面 Abdul 建议的文档。但是我似乎无法在我的模型中获得关系参考。根据帖子使用“fields.GenericRelation(Faves)”但显然与我的应用程序以及按照他们的建议阅读文档时。它不会显示在管理员中。有什么想法吗?
  • @FlawlessCalamity 管理员中没有显示什么,你能指定吗?

标签: django postgresql django-models django-postgresql


【解决方案1】:

您可以使用内容类型框架。这是一个link 供您参考

【讨论】:

  • 非常感谢,请看我上面对@Marco 的评论,也许你有什么想法?
猜你喜欢
  • 1970-01-01
  • 2013-06-25
  • 2012-11-26
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-23
  • 1970-01-01
相关资源
最近更新 更多