You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目报错NameError: name 'Topic' is not defined求助

解决Django NameError: name 'Topic' is not defined问题

核心原因

你代码里实际定义的模型类是Lesson,但在Entry类的ForeignKey里关联的是未定义的Topic类,名字不匹配导致Django找不到对应的模型。

两种修复方案

方案1:回归原计划(使用Topic+Entry)

把Lesson类重命名为Topic,并修正Entry里的关联:

from django.db import models

class Topic(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.text

class Entry(models.Model):
    # 关联正确的Topic类
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        return self.text[:50] + "..."

执行迁移更新数据库:

python manage.py makemigrations courses
python manage.py migrate

方案2:改用Lesson+Entry

如果确定要保留Lesson类,修改Entry里的关联对象为Lesson:

from django.db import models

class Lesson(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.text

class Entry(models.Model):
    # 关联Lesson类
    lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        return self.text[:50] + "..."

同样执行迁移:

python manage.py makemigrations courses
python manage.py migrate

额外排查点

  • 检查模型类名拼写:确保类名首字母大写(如Topic而非topic),无拼写错误
  • 确认courses已添加到项目settings.py的INSTALLED_APPS列表中
  • 若迁移文件混乱,可删除courses/migrations/目录下除__init__.py外的所有文件,重新执行迁移(仅开发环境适用,会清空该应用数据表)

内容的提问来源于stack exchange,提问作者Swyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 12:15:04