gpt4 book ai didi

django - select_related 字段的调用管理器

转载 作者:行者123 更新时间:2023-12-04 07:18:00 25 4
gpt4 key购买 nike

我有以下示例:

class Profile(models.Model):
...

class Person(models.Model):
profile = models.ForeignKey(Profile, ...)
我有一个用于 Profile 类的复杂模型管理器,我构建了一个 View 来列出大量人员。我尝试计算数据库中的所有内容,因此我想从 Person QuerySet 调用配置文件管理器。
为此,我需要执行以下操作:
Person.objects.filter(...).select_related('profile', queryset=Profile.objects.with_computed_revenue().all())
然后我应该能够从 SQL 中检索到 person.profile.computed_revenue,函数“with_computed_revenue”是 ProfileManager 的一个函数,用于注释computed_revenue。
最终目标是亲自添加查询集:
.values('profile__computed_revenue')
Prefetch for prefetch_related 似乎是可能的,但我找不到与 select_related 的等效项。

最佳答案

如果我理解正确的话,正如 Django 文档在 https://docs.djangoproject.com/en/3.2/ref/models/querysets/#prefetch-related 中所说的那样:

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related.


您应该使用 select_related用于 FK 关系和 prefetch_related对于多对一关系
在您的情况下, Person模型与 Profile 具有多对一关系,因此您必须使用 prefetch_related

关于django - select_related 字段的调用管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68679519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com