Django:在1到N模型中,是否有一种查找相关对象的简单方法?(Django: in a 1 to N model, is there a simple way to look up related

编程入门 行业动态 更新时间:2024-10-26 00:31:22
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().

更多推荐

本文发布于:2023-08-05 03:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1427981.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有一种   模型   对象   简单   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!