python - 如何通过django中的多级反向外键获取相关对象查询集?

标签 python django django-models foreign-keys django-queryset

我有一个这样的模型:

class Publisher(models.Model):
    ...

class Author(models.Model):
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

class Article(models.Model):
    author= models.ForeignKey(Author, on_delete=models.CASCADE)

现在我正在尝试从给定的发布者“pub”获取所有文章。 我试过执行以下操作:

pub.article_set()

pub.authot_set().article_set()

以及其他失败的尝试。那么,如何在不多次访问数据库的情况下检索给定发布者的所有文章的查询集呢?什么是最有效的方法?

提前致谢!

最佳答案

减少数据库查询数量的最有效方法是对文章的查询集进行过滤。

# pub is the instance of Publisher
articles = Article.objects.filter(author__publisher=pub)

关于python - 如何通过django中的多级反向外键获取相关对象查询集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066789/

相关文章:

Python使用urllib读取google搜索结果

Python + BeautifulSoup : How to get wrapper out of HTML based on text?

django - 将模型的实例传递给 django 表单集

python - 在django中直接提供外键值

python - Django 项目结构,跨应用程序共享扩展 auth "User"模型的推荐结构?

python - 如何在 Raspbian Buster 上使用 headless Firefox 设置 Selenium

python - 连接未创建到 mongoengine 中的新 dbname

Django - 如何确定模型类是否是抽象的

python django 休息框架。如何以某种特定格式序列化外键 UUID?

python - Django : Foreign key set not found after saving object