1

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!

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

2 Comments

but now Post not defined! :)
ah. you should not cross-reference models, it makes no sense. Did not see this, sorry. Add only one reference from Category to Post and you are done. Will update the source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.