Reputation: 53
class Blog(models.Model):
name = models.CharField()
def get_posts_belonging_to_this_blog_instance(self):
return Post.objects.filter(blog__exact=self.id)
class Category(models.Model):
name = models.CharField()
def get_posts_with_this_category(self):
return Post.objects.filter(category__exact=self.id)
class Post(models.Model):
blog = models.ForeignKey(Blog)
category = models.ForeignKey(Category)
text = models.TextField()
Best way to explain it with code, is there a more Django approach to doing this?
Upvotes: 1
Views: 597
Reputation: 32250
First, note these relations aren't 1 to 1, they're 1 to N or N to 1, depending on which way you look.
In order to access all posts from a Category or a Blog, you can simply use your_category.post_set.all()
. If you want to change this property name, you can define Post like this:
blog = models.ForeignKey(Blog, related_name="posts")
category = models.ForeignKey(Category, related_name="posts")
And then access using your_category.posts.all()
or your_blog.posts.all()
.
Upvotes: 4