【问题标题】:Has Many Through in django?在 django 中有很多通过吗?
【发布时间】:2023-02-11 12:47:53
【问题描述】:
class Post(models.Model):
    ...

class Comment(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE)

class Tag(models.Model):
    comment = models.ForeignKey(Comment,on_delete=models.CASCADE)

如何使用post对象获取所有标签???

像 laravel 框架 hasManyThrough?

除了这种方式

for comment in post.comment_set.all():
    for tag in comment.tag_set.all():
        print(tag)

【问题讨论】:

    标签: python django orm relationship


    【解决方案1】:

    由于这是反向查找,您可以使用prefetch_related

    Post.objects.filter(your_condition)
    .prefetch_related(Prefetch("comment_set"),
     queryset=Comment.objects.prefetch_related("tag_set"))
    

    您可以根据您的条件设置查询集。

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多