Skip to main content
 首页 » 编程设计

python之如何定义一个引用自身的 Django 模型

2025年05月04日36tintown

我是 Django 的新手,目前正在编写一个应用程序,用户可以在其中输入他们对某个主题的意见。

每个观点 A 可能有零个或多个支持 A 的观点和几个(零个或多个)反对 A 的观点。

我试图为此创建一个模型并编写了一个 models.py 文件,如下所示:

from django.db import models 
 
# Create your models here. 
class Opinion(models.Model): 
    id = models.AutoField(primary_key=True) 
    contents = models.CharField(max_length=256) 
    source = models.CharField(max_length=256) 
    proArguments = models.ManyToManyField(Opinion, verbose_name="Pro arguments") 
    contraArguments = models.ManyToManyField(Opinion, verbose_name="Contra arguments") 

当我运行 python manage sqlall 时,出现以下错误:

  File "D:\dev\history-site\history_site\opinions\models.py", line 4, in <module> 
    class Opinion(models.Model): 
  File "D:\dev\history-site\history_site\opinions\models.py", line 8, in Opinion 
    proArguments = models.ManyToManyField(Opinion, verbose_name="Pro arguments") 
 
NameError: name 'Opinion' is not defined 

我该如何修复这个错误?

请您参考如下方法:

来自 docs of ManyToManyField :

Requires a positional argument: the class to which the model is related. This works exactly the same as it does for ForeignKey, including all the options regarding recursive and lazy relationships.

哪个says :

To create a recursive relationship -- an object that has a many-to-one relationship with itself -- use models.ForeignKey('self').

所以:

proArguments = models.ManyToManyField("self", verbose_name="Pro arguments") 
contraArguments = models.ManyToManyField("self", verbose_name="Contra arguments") 

如果参数也被视为意见,我有点想知道你的数据模型,但这是另一回事。