【问题标题】:Recursive relationship in Django: get all the interrelated records from each recordDjango中的递归关系:从每条记录中获取所有相互关联的记录
【发布时间】:2021-01-18 15:45:23
【问题描述】:

我有这个模型用于曲调:

class MsTune(models.Model):

    name = models.CharField(max_length=255)
    ms = models.ForeignKey(Manuscript, on_delete=models.CASCADE, related_name="mstunes")
    concordances = models.ManyToManyField("self", blank=True)

我有很多手稿 (ms),同一曲调可能会出现在不止一份手稿中。我想要做的是,使用 concordances 字段,链接所有相似的曲调。这部分有效。 Django 管理后端允许我选择许多曲调以链接到我正在编辑的当前曲调:

问题是我想查看我在每首曲子中链接的所有曲子。例如,在上面的示例中,Mary Scott... 应该列出所有三首曲调(Courante、Almain、Hopetounsetc...); Courante 应该列出其他三个(Mary Scott、Almain、Hopetoun's)。现在它们只显示我添加它们的编辑页面。我错过了什么?我必须创建一个新的concordances 模型吗?

附言

指定 symmetrical=True 没有帮助。

更好地解释我想要实现的目标

如果我有这些曲调:

tune_1
tune_1a
tune_1b
tune_2

现在我得到了这个:

tune_1:
concordances.all: tune_1a, tune_1b

tune_1a:
concordances.all: tune_1

tune_1b:
concordances.all: tune_1

我想要这个:

tune_1:
concordances.all: tune_1a, tune_1b

tune_1a:
concordances.all: tune_1, tune_1b

tune_1b:
concordances.all: tune_1, tune_1a

使用中间模型的部分解决方案

假设我使用中间模型:

class MsTune(models.Model):

    related = models.ManyToManyField('MsTune', through='Concordance', blank=True)
[...]

class Concordance(models.Model):
    tune = models.ManyToManyField(MsTune)
    title = models.CharField(max_length=64)

    def __str__(self):
        return self.title

然后,我如何在显示特定曲调详细信息的模板中访问相关曲调列表?

{% for concordance in tune.concordance_set.all %} {{ concordance__mstune_id }}{% endfor %}

不输出任何东西; [...]{{ concordance }}[...] 输出的是索引名称,而不是每首曲子的标题。

访问{{ tune.concordances }} 给我一个'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' 错误。

【问题讨论】:

    标签: django django-models django-admin django-managers


    【解决方案1】:

    我通过创建不同的模型来解决:

    class Concordance(models.Model):
        name = models.CharField(max_length=64)
        tunes = models.ManyToManyField(MsTune, related_name="concordances")
    
        def __str__(self):
            return self.name
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-21
      • 2017-04-22
      • 2015-06-18
      • 2013-12-22
      • 2017-07-25
      • 1970-01-01
      • 2012-08-08
      • 2020-09-03
      相关资源
      最近更新 更多