Django:在1到N模型中,有没有一种简单的方法来查找相关对象?

Django:在1到N模型中,有没有一种简单的方法来查找相关对象?,django,django-models,Django,Django Models,用代码来解释它的最好方法是,有没有一种更为Django的方法来实现这一点?首先,请注意这些关系不是1对1,而是1对N或N对1,这取决于您的观察方式 博客可以有很多帖子-1到N 类别可以有许多帖子-1到N 一篇文章属于一个类别,但一个类别可以有多篇文章-N到1。如果一个类别只能有一个帖子,那么它将是1对1——这是一种排他性的关系,就像一对一夫一妻制的夫妻:——) 要访问某个类别或博客中的所有帖子,只需使用your\u Category.post\u set.all()。如果要更改此属性名称,可

用代码来解释它的最好方法是,有没有一种更为Django的方法来实现这一点?

首先,请注意这些关系不是1对1,而是1对N或N对1,这取决于您的观察方式

  • 博客可以有很多帖子-1到N
  • 类别可以有许多帖子-1到N
  • 一篇文章属于一个类别,但一个类别可以有多篇文章-N到1。如果一个类别只能有一个帖子,那么它将是1对1——这是一种排他性的关系,就像一对一夫一妻制的夫妻:——)
要访问某个类别或博客中的所有帖子,只需使用
your\u Category.post\u set.all()
。如果要更改此属性名称,可以按如下方式定义Post:

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

然后使用
your_category.posts.all()
your_blog.posts.all()

首先,请注意这些关系不是1对1,而是1对N或N对1,具体取决于您的观察方式

  • 博客可以有很多帖子-1到N
  • 类别可以有许多帖子-1到N
  • 一篇文章属于一个类别,但一个类别可以有多篇文章-N到1。如果一个类别只能有一个帖子,那么它将是1对1——这是一种排他性的关系,就像一对一夫一妻制的夫妻:——)
要访问某个类别或博客中的所有帖子,只需使用
your\u Category.post\u set.all()
。如果要更改此属性名称,可以按如下方式定义Post:

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

然后使用
your_category.posts.all()
your_blog.posts.all()

访问。请记住
post\u set
(或
posts
,如果使用相关的_名称)是一个管理器,而不是直接属性。因此,要从一个类别中获取所有相关帖子,您需要执行
your\u category.post\u set.all()
@Daniel:ohh,我忘了这个细节。现在更新。非常感谢。请记住,
post\u set
(或
posts
,如果使用相关的\u名称)是一个管理器,而不是一个直接属性。因此,要从一个类别中获取所有相关帖子,您需要执行
your\u category.post\u set.all()
@Daniel:ohh,我忘了这个细节。现在更新。非常感谢。