为什么我一直获取名称错误:名称“PS”未定义

2024-03-28 08:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,在我的模型.py我刚创建的文件:

class PL(models.Model):
  created = models.DateTimeField(default=timezone.now)
  owner = models.ForeignKey(User, related_name='PL')
  text = models.CharField(max_length=2000, blank=True)
  rating = models.IntegerField(default=0)
  pal = models.ManyToManyField(PS, blank=True, null=True)
  class Meta:
    verbose_name = "PL text"
  def __unicode__(self):
    return self.user

class PS(models.Model):
  Original = models.ForeignKey(PL, related_name='OPL', blank=True)
  rating = models.IntegerField(default=0)
  word = models.CharField(max_length=50, blank=True)

  def __unicode__(self):
    return "Word: %s" % (self.word)

但是我一直得到:NameError:name'PS'没有定义

为什么会这样?在


Tags: textnameselftruedefaultmodelmodelsmax
2条回答

课内PL:

pal = models.ManyToManyField(PS, blank=True, null=True)

您正在尝试使用PS,但它还没有创建,因为python脚本从上到下读取。通常,解决方案是在PL之前定义PS,但这对您无效,因为PS也依赖于PL

^{pr2}$

你把自己逼到了鸡毛蒜皮的角落。你需要一只鸡,但是没有鸡蛋你是买不到的,但是没有鸡你就不能得到鸡蛋,但是。。。在

最终,您需要进行一些重构,以便这两个类不相互依赖。在

注意,这个问题不会发生在方法中,因为在这种情况下,方法类直到它们被运行才被查找,但是,由于类名称空间在创建类时被执行,所以有一个NameError。在

就像mgilson说的,这是自上而下的。但是Django有办法克服它-

pal = models.ManyToManyField('PS', blank=True, null=True)

Django doc在ForeignKey下描述了它。在

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself.

你可以read more here。在

相关问题 更多 >