Reputation: 8992
I'm very new to Python and Django. I'm trying to create a basic blog engine containing categories, posts and tags.
A category will have multiple posts
A post will have multiple tags
So i designed my models like this:
from django.db import models
class Category(models.Model):
category_name = models.CharField(max_length=200)
posts = models.ManyToManyField(Post)
def __str__(self):
return self.category_name
class Post(models.Model):
post_title = models.CharField(max_length=200)
post_body = models.TextField()
post_tags = models.ManyToManyField(Tag)
def __str__(self):
return self.post_title
class Tag(models.Model):
tag_title = models.CharField(max_length=200)
def __str__(self):
return self.tag_title
When i run python manage.py migrate
command, i am getting
File "/Development/Projects/pBlog/blogEngine/models.py", line 6, in Category
posts = models.ManyToManyField(Post)
NameError: name 'Post' is not defined
Error. Is there any syntax error? I have .Net background i might need to change my whole approach.
Upvotes: 3
Views: 2592
Reputation: 3
The problem is that you have defined class Category before you defined class Post - and you are calling Post id from Category. just cut it out (class Category), and paste it under class Post
Upvotes: 0
Reputation: 9594
The Post class is not yet defined when you refer to it on line 6. In this situation, you should use the name of the model instead:
class Category(models.Model):
category_name = models.CharField(max_length=200)
posts = models.ManyToManyField("Post")
def __str__(self):
return self.category_name
This is documented here: https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.ForeignKey.
Upvotes: 6