这是我的情况: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/

10-16 22:47