django - 如何在预取的模型上选择相关?
问题描述
是否可以选择作为您正在预取的模型的外键的相关模型?
一组示例模型:
class Book(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey('Author', related_name='books')
publisher = models.ForeignKey('Publisher')
class Author(models.Model):
name = models.CharField(max_length=50)
type = models.IntegerField() # choices= omitted for brevity
class Publisher(models.Model):
name = models.CharField(max_length=50)
然后是查询:
authors = Author.objects.filter(type=10)
authors = authors.prefetch_related('books')
# I tried both of these (but not at the same time):
authors = authors.select_related('publisher') # doesn't work
authors = authors.select_related('books__publisher') # also doesn't work
在这两种情况下,我都会收到 FieldError:
Invalid field name(s) given in select_related
这是有道理的,因为 publisher 或 books__publisher 都与起始模型(Authors)无关。但我不确定如何表明我想在预取模型(书籍)而不是起始模型(作者)上执行 select_related。
我确实看过Prefetch objects,但我看不出这些会有什么帮助。
解决方案
您可以将多个参数传递给prefetch
方法。试试这个:
authors = Author.objects.filter(type=10)
authors = authors.prefetch_related('books', 'books__publisher')
推荐阅读
- sql - postgresql 计数唯一性
- django - Django/Celery 4.3 - 工作似乎随机失败
- java - 使用 Java 代码的 zip 文件中的 Blob 数据文件
- java - 如何在折线内添加文本?
- javascript - 如何使用表单更改 Javascript 代码中变量的值
- react-native - 为什么 styled-components 5.x 会警告“预期样式包含单位”。
- class - 不包括成员函数和继承,向类添加功能的一些最常见的编程模式是什么?
- c# - VS 2019 中的“修复”Android SDK Manager 失败
- php - Laravel 6.x 通过从 Axios 调用获取当前用户来设置 auth()->user()
- python - 创建新线程时停止旧线程