【问题标题】:Multiple ForeignKeys in Through model for Many-to-many relation to same model通过模型中的多个外键用于与同一模型的多对多关系
【发布时间】:2014-01-12 18:56:04
【问题描述】:

我通过一个名为 RelatedResource 的中间模型从名为 Resource 的模型与自身建立了多对多关系:

class Resource(TimeStampedModel):
    title = models.CharField(max_length=100, unique=True) # book title, person's name, video title, etc.
    description = models.TextField(max_length=500, null=True, blank=True)
    link = models.URLField(max_length=500, blank=True, null=True) # dynamically generated for youtube and amazon; todo: uniqueness
    resourceID = models.CharField(max_length=20, blank=True, null=True) # todo: uniqueness
    picture = models.URLField(max_length=500, blank=True)
    tags = TaggableManager()
    ...

class RelatedResource(models.Model):
    input = models.ForeignKey(Resource, related_name="input_resource")
    output = models.ForeignKey(Resource, related_name="output_resource")
    input_affiliate = models.ForeignKey(Resource, related_name="while_with", blank=True, null=True)
    reason = models.CharField(max_length=500)
    ...

Django 抱怨说 Resource 有超过 2 个外键是不明确的,当然,因为它不知道三个 ForeignKey 字段中的哪两个应用于多对多关系。

有什么方法可以将所有 3 个 ForeignKey 字段保留在中间模型中,并告诉 Django 哪些 2 个用于多对多关系?

【问题讨论】:

    标签: django django-models many-to-many


    【解决方案1】:

    我认为您正在尝试做的是递归关系。 它在此处进行了描述。 https://docs.djangoproject.com/en/1.6/ref/models/fields/#recursive-relationships

    在这里。 Django recursive relationship

    【讨论】:

    • 似乎递归关系是多对一的。我需要 M2M。我最终摆脱了 M2M 关系并保留了 3 个 ForeignKey 关系。到目前为止一切正常。
    猜你喜欢
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    相关资源
    最近更新 更多