Django NameError during ManyToMany field referencing

荒凉一梦 提交于 2019-12-12 21:44:57

问题


I am having a table named PlayCat. which basically stores al the category names of playful activities. such as disco,pool n stuff. So i want these categories to b referenced(ManyToMany) when a user creates a Play arena where he/she can select al the categories it belongs to.

Play :

class Play(models.Model):
  shopname=models.CharField(max_length=100)
  desc=models.CharField(max_length=500,blank=True, null=True)
  address=models.CharField(max_length=300)
  category = models.ManyToManyField(PlayCat)
  url=models.URLField(blank=True, null=True)
  email=models.EmailField(blank=True, null=True)
  slug=models.SlugField(blank=True, null=True)
  phone=models.CharField(max_length=40,blank=True, null=True)

  def __unicode__(self):
    return self.shopname

and in the same models.py I have 'PlayCat'

class PlayCat(models.Model):
  cat = models.CharField(max_length=45)
  def __unicode__(self):
    return self.cat

I have also populated the PlayCat database but when i add M2M referencing error message appears in the terminal saying

_import__(name)
  File "/home/saud/Downloads/Django-1.2.3/ms/ms/ms/sale/models.py", line 104, in <module>
    class Play(models.Model):
  File "/home/saud/Downloads/Django-1.2.3/ms/ms/ms/sale/models.py", line 108, in Play
    category = models.ManyToManyField(PlayCat)
NameError: name 'PlayCat' is not defined

I dont understand why is the NameError and wat i have not defined. Please help. Thank You.


回答1:


I guess it's because you have a model PlayCat defined after a model Play. So it can't resolve it.

You can either put model PlayCat before Play or use a string for reference

category = models.ManyToManyField('PlayCat')


来源:https://stackoverflow.com/questions/5618720/django-nameerror-during-manytomany-field-referencing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!