user401377
user401377

Reputation: 53

Django: in a 1 to N model, is there a simple way to look up related objects?

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

Answers (1)

jweyrich
jweyrich

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.

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

Upvotes: 4

Related Questions