简体   繁体   中英

Why I keep getting NameError: name 'PS' is not defined

Ok, in my models.py file I've just created this:

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

Why is this happening?

Like mgilson says, It goes top to bottom. But Django has a way to overcome it by doing this -

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

Django doc describes it under 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:

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. Normally, the solution would be to just define PS before PL , but that won't work for you since PS depends on PL too:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM