views:

51

answers:

1
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?

+4  A: 

First, note these relations aren't 1 to 1, they're 1 to N or N to 1, depending on which way you look.

  • Blog can have many posts - 1 to N.
  • Category can have many posts - 1 to N.
  • A Post belongs to a single category, but a category can have many posts - N to 1. If a category could have only 1 Post, then it would be 1 to 1 - it's an exclusive relationship, like a monogamous couple :-)

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().

jweyrich
Bear in mind that `post_set` (or `posts`, if you use related_name) is a manager, not a direct attribute. So to actually get all the related posts from a category you need to do `your_category.post_set.all()`.
Daniel Roseman
@Daniel: ohh, I forgot this detail. Updating now. Thank you!
jweyrich