python - Django 模型中的外键

标签 python django

这是我的情况:SubCategory 有指向 Topic 的外键,Topic 有指向 SubCategory 的外键。

class SubCategory(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=110)
    description = models.TextField(default='')
    ordering = models.PositiveIntegerField(default=1)
    category = models.ForeignKey(Category)
    created_on = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User)
    updated_on = models.DateTimeField(blank=True, null=True)
    updated_by = models.ForeignKey(User, related_name='+')
    num_topics = models.IntegerField(default=0)
    num_posts = models.IntegerField(default=0)
    last_topic = models.ForeignKey(Topic, related_name='+')


class Topic(models.Model):
    name = models.CharField(max_length=300)
    slug = models.SlugField(max_length=300)
    description = models.TextField(default='')
    subcategory = models.ForeignKey(SubCategory)
    created_on = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User)
    updated_on = models.DateTimeField(blank=True, null=True)
    updated_by = models.ForeignKey(User, related_name='+')

当我运行这段代码时,出现以下错误:

NameError: name 'Topic' is not defined.

有人能告诉我怎么解决吗?

最佳答案

要么将 Topic 放在引号中:"Topic"

last_topic = models.ForeignKey("Topic", related_name='+')

或者将 Topic 类放在 SubCategory 类之上

关于python - Django 模型中的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19071570/

相关文章:

python - 如何在 Pygame 中的特定时刻开始播放音乐

python,django,通过FK显示正确的字段名称,链接表

django - 如何将 django csrf token 直接嵌入到 HTML 中?

python - 在一段时间内有条件

python - xpath表达式 "html/body/div/text()[1]"的结果是: [object Text].它应该是使用Selenium打印元素文本的元素错误

python - 解决模型时如何使 pyomo 静音(详细程度 0)

python - 如何在 PyCharm 项目 View 中隐藏 venv

python - 如何根据 page1 上的选择在 page2 上生成动态 MultipleChoiceField 选项?

python - 使用标准 django.contrib.auth.models.User 模型在 Sqlite 数据库中查询用户名 "x"的用户

python - Django : order queryset by model method without converting to list