Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign Key in Django model

Tags:

python

django

Here is my situation: SubCategory has foreign key to Topic and Topic has foreign key to 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='+')

When I run this code, it gives the following error:

NameError: name 'Topic' is not defined.

Can anybody tell me how to fix it?

like image 316
asit_dhal Avatar asked Sep 28 '13 20:09

asit_dhal


1 Answers

Either put Topic in quotes: "Topic"

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

or put the Topic class above the SubCategory class

like image 89
Timmy O'Mahony Avatar answered Sep 30 '22 22:09

Timmy O'Mahony