0

还是个新手,我得改编一个 Django (v1.10) 脚本。原始脚本使用一个主类“倡议”,它可以有任意数量的“支持者”。

我必须做出的调整包括沿着“倡议”(类似的行为,不同的领域)拥有另一个名为“策略”的主类。我在“倡议”和“政策”上坚持使用 ManyToManyField,它应该指向我试图使用 GenericRelation 来支持两个主要类的支持者。我收到以下错误消息:

initproc.Supporter: (fields.E336) The model is used as an intermediate model by 'initproc.Initiative.supporters', but it does not have a foreign key to 'Initiative' or 'User'.
initproc.Supporter: (fields.E336) The model is used as an intermediate model by 'initproc.Policy.supporters', but it does not have a foreign key to 'Policy' or 'User'.

我的models.py(删除了所有不相关的内容)之前:

# ------------------------------ Initiative ------------------------------------
class Initiative(models.Model):

  supporters = models.ManyToManyField(User, through="Supporter")


# ------------------------------- Supporter -------------.----------------------
class Supporter(models.Model):

  class Meta:
    unique_together = (("user", "initiative"),)

  user = models.ForeignKey(User)
  initiative = models.ForeignKey(Initiative, related_name="supporting")

在我的修改之后:

# ------------------------------- Supporter ------------------------------------
class Supporter(models.Model):

  class Meta:
    unique_together = (("user", "target_type", "target_id"),)

  user = models.ForeignKey(User)

  target_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  target_id = models.IntegerField()
  target = GenericForeignKey('target_type', 'target_id')

# -------------------------------- Policy --------------------------------------
class Policy(PolicyBase):

  supporters = models.ManyToManyField(User, through="Supporter")

# ------------------------------ Initiative ------------------------------------
class Initiative(models.Model):

  supporters = models.ManyToManyField(User, through="Supporter")

引发上述错误。我想我理解问题不是用户的外键(没有改变),而是我试图让支持者为倡议和政策工作。我只能找到through_fields寻找解决方案,但我认为我也在寻找错误的地方。

问题:
如何设置指向 ManyToManyField 上多个类的 GenericForeignKey?我也想知道我现在必须把related_name 参数放在哪里。

4

0 回答 0