JohnSmith
JohnSmith

Reputation: 59

Models in Django, is not defined

So, i have posts, and category:

class Post(models.Model):
    ...
    category = models.ForeignKey(Category)

    def __unicode__(self):
        return self.title

class Category(models.Model):
    category = models.CharField(max_length = 30, unique=True)
    id_post = models.ForeignKey(Post)   

    def __unicode__(self):
        return self.category

i write

python manage.py validate

and NameError: Name Category is not defined. WHY???

i`m use sqllite, thanks!

Upvotes: 1

Views: 1616

Answers (1)

Thomas Kremmel
Thomas Kremmel

Reputation: 14783

Place Category above Post in models.py. Django / Python validates the models from top to down. I also stumbled over it when beginning with Django :)

class Category(models.Model):
    category = models.CharField(max_length = 30, unique=True)   

    def __unicode__(self):
        return self.category

class Post(models.Model):
    ...
    category = models.ForeignKey(Category)

    def __unicode__(self):
        return self.title

As you placed in your source code a relationship from Post to Category you probably intended to have a relationship from a category instance to all related post instances. This is build-in in Django and you can reverse ForeignKey relationships using the 'modelname_set' attribute.

So to get all posts which are assigned to a specific Category you can do:

myCategory =Category.objects.get(pk=1)
myCategory.post_set.all()

Upvotes: 2

Related Questions