NameError:未定义名称“Tag”

时间:2012-12-01 00:46:00

标签: python django nameerror

我正在为我的django网站创建模型(python,如果这不是很明显的话)。

from django.db import models

class Picture(models.Model):
        name = models.CharField(max_length=100)
        pub_date = models.DateTimeField('date published')
        tags = models.ManyToManyField(Tag)
        owner = models.ForeignKey(User)

class Tag(models.Model):
        pics = models.ManyToManyField(Picture)
        name = models.CharField(max_length=30)

class User(models.Model):
        name = models.CharField(max_length=20)
        date_joined = models.DateTimeField('date joined')

class Comment(models.Model):
        content = models.CharField(max_length=500)
        date = models.DateTimeField('date commented')
        commenter = models.ForeignKey(User)
        pic = models.ForeignKey(Picture)

这是整个当前模型,但我在行tags = models.ManyToManyField(Tag)上收到错误,说“NameError:name'Tag'未定义”

与此有什么关系?

1 个答案:

答案 0 :(得分:1)

声明图片后声明标记,但图片使用标记,因此在您尝试使用标记时未定义标记。只需改变课程的顺序即可解决问题。

换句话说,将您的代码更改为:

class Tag(models.Model):
    pics = models.ManyToManyField(Picture)
    name = models.CharField(max_length=30)

# Hurray, Tag exists now

class Picture(models.Model):
    name = models.CharField(max_length=100)
    pub_date = models.DateTimeField('date published')

    # Therefore, this next line will work

    tags = models.ManyToManyField(Tag)
    owner = models.ForeignKey(User)

(减去我的评论)