Django:在1到N模型中,是否有一种查找相关对象的简单方法?(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()
用代码解释它的最佳方法是,有更多的Django方法来做到这一点吗?
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?
最满意答案
首先,请注意这些关系不是1比1,它们是1到N或N比1,这取决于你看的方式。
博客可以有很多帖子 - 从1到N. 类别可以有很多帖子 - 从1到N. 一个帖子属于一个类别,但一个类别可以有很多帖子 - N到1.如果一个类别只有1个帖子,那么它将是1比1 - 它是一个独家关系,就像一对一夫一妻:-)要访问类别或博客中的所有帖子,您只需使用your_category.post_set.all() 。 如果要更改此属性名称,可以像这样定义Post:
blog = models.ForeignKey(Blog, related_name="posts") category = models.ForeignKey(Category, related_name="posts")然后使用your_category.posts.all()或your_blog.posts.all() 。
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().
更多推荐
发布评论