select_相关字段的调用管理器

Que*_*ier 5 django

我有以下示例:

class Profile(models.Model):
    ...

class Person(models.Model):
    profile = models.ForeignKey(Profile, ...)
Run Code Online (Sandbox Code Playgroud)

我有复杂的 Profile 类模型管理器,并且我构建了一个视图来列出大量人员。我尝试计算数据库中的所有内容,因此我想从 Person QuerySet 调用配置文件管理器。

为此,我需要执行以下操作:

Person.objects.filter(...).select_related('profile', queryset=Profile.objects.with_computed_revenue().all())
Run Code Online (Sandbox Code Playgroud)

然后我应该能够从 SQL 中检索 person.profile.compulated_revenue,其中函数“with_compulated_revenue”是 ProfileManager 的一个函数,用于注释compulated_revenue。

最终目标是添加亲自查询集:

.values('profile__computed_revenue')
Run Code Online (Sandbox Code Playgroud)

使用 Prefetch 来实现 prefetch_lated 似乎是可能的,但我找不到与 select_lated 等效的内容。

小智 1

如果我正确理解了你的意思,正如 Django 文档在https://docs.djangoproject.com/en/3.2/ref/models/querysets/#prefetch-lated中所说:

\n
\n

select_lated 的工作原理是创建 SQL 连接并将相关对象的字段包含在 SELECT 语句中。因此,select_lated 会在同一个数据库查询中获取相关对象。但是,为了避免通过连接 \xe2\x80\x98many\xe2\x80\x99 关系而产生更大的结果集,select_lated 仅限于单值关系 - 外键和一对一。\nprefetch_lated另一方面,对每个关系进行单独的查找,并在 Python 中执行 \xe2\x80\x98joining\xe2\x80\x99 。这使得它可以预取多对多和多对一对象,这是使用 select_lated 无法完成的,除了 select_lated 支持的外键和一对一关系之外。

\n
\n

您应该用于select_relatedFK 关系和prefetch_related多对一关系

\n

在您的情况下,Personmodel 与 具有多对一关系Profile,因此您必须使用prefetch_related

\n