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()
Source:stackexchange.com