如何设置一个指向ManyToManyField上多个类的Django GenericForeignKey?

时间:2018-08-26 13:39:34

标签: python django django-models many-to-many generic-foreign-key

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

我必须进行的适应包括在“主动”(类似的行为,不同的领域)中拥有另一个名为“策略”的主类。我在“ initiative”和“ policy”上停留在ManyToManyField上,它应该指向Supporters,在这里我试图使用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")

这将引发以上错误。我想我了解的问题不是用户的ForeignKey(未更改),而是我试图使Supporter同时适用于Initiative和Policy。我只能找到through_fields寻找解决方案,但我想我也在寻找错误的地方。

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

0 个答案:

没有答案