[英]Why I keep getting NameError: name 'PS' is not defined
Ok, in my models.py file I've just created this: 好的,在我的models.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)
but I keep getting: NameError: name 'PS' is not defined 但我不断得到:NameError:未定义名称“ PS”
Why is this happening? 为什么会这样呢?
Like mgilson says, It goes top to bottom. 就像mgilson所说,它从上到下。 But Django has a way to overcome it by doing this -
但是Django可以通过这样做来克服它-
pal = models.ManyToManyField('PS', blank=True, null=True)
Django doc describes it under ForeignKey. Django文档在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.
如果需要在尚未定义的模型上创建关系,则可以使用模型的名称,而不是模型对象本身。
You can read more here . 您可以在这里阅读更多内容 。
In class PL: 在PL类中:
pal = models.ManyToManyField(PS, blank=True, null=True)
You're tyring to use PS, but it hasn't been created yet as the python script gets read from top to bottom. 您打算使用PS,但由于python脚本是从上至下读取的,因此尚未创建。 Normally, the solution would be to just define
PS
before PL
, but that won't work for you since PS
depends on PL
too: 通常,解决方案是只在
PL
之前定义PS
,但这对您不起作用,因为PS
依赖于PL
:
Original = models.ForeignKey(PL, related_name='OPL', blank=True)
You've backed yourself into a chicken-egg corner. 您已将自己置身于鸡蛋角。 You need a chicken, but you can't get it without an egg -- but you can't get an egg without a chicken, but ...
您需要一只鸡,但没有鸡蛋就无法得到-但是没有鸡肉就不能得到鸡蛋,但是...
Ultimately, you need to do some refactoring so that the two classes don't depend on each other. 最终,您需要进行一些重构,以使这两个类不相互依赖。
Note that the problem doesn't happen within methods since in that case, the methods classes aren't looked up until they are run -- However, since the class namespace gets executed when the class is created, you have a NameError
. 请注意,问题不会在方法内发生,因为在那种情况下,直到运行它们时才查找方法类-但是,由于类名称空间是在创建类时执行的,因此存在
NameError
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.