I’m putting together a model for a blog app.
Here’s the model:
from django.db import models
class Tag(models.Model):
keyword = models.CharField(max_length=256)
posts = models.ManyToManyField(Post)
def __unicode__(self):
return self.keyword
class Post(models.Model):
title = models.CharField(max_length=512)
image = models.ImageField
body = models.TextField()
visible = models.BooleanField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
def __unicode__(self):
return self.title
I added the blog package to settings.py. Then I ran python manage.py sql blog. I got the following errors:
File "/pathto/blog/models.py", line 5, in Tag
posts = models.ManyToManyField(Post)
NameError: name 'Post' is not defined
I don’t understand why Post is not defined because I am defining it in the models.py file. What am I missing?
Problem
When you are defining
Tagclass,Postclass is not yet defined. Because you are referring to it, you getNameErrorexception.Solution
Thus, change this line:
into this line:
Explanation
The documentation gives you walkaround:
Alternative solution
You can also omit definition of
postsinTagclass (the line “posts = models.ManyToManyField(Post)“) and just provide the appropriate name for reverse relation inPostmodel. Django will know what to do with it. Just replace this line:with this line:
To learn more, read about
related_nameargument when defining relations (ForeignKeyandManyToManyField).