简体   繁体   English

如何在 django 中以反向通用关系预取或使用 select 相关?

[英]How to prefetch or use select related in reverse generic relation in django?

Assume i have two models:假设我有两个模型:

class A:
  content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True, blank=True)
  object_id = models.PositiveIntegerField(null=True, blank=True)
  attached_object = fields.GenericForeignKey('content_type', 'object_id')
class B:
  some_field = GenericRelation(class A)

Now I have a scenario where i need to list all of class B instances, and in that result list, i need to include some of class A which is related to class B. While trying to do that, obviously it is leading to as many query hits as there are instances of class B. I have searched all online forums to try and reduce queries in this case.现在我有一个场景,我需要列出所有 B 类实例,并且在该结果列表中,我需要包括一些与 B 类相关的 A 类。在尝试这样做时,显然它会导致尽可能多的查询命中,因为有 B 类的实例。在这种情况下,我搜索了所有在线论坛以尝试减少查询。

instances_of_b = B.objects.all()
for instance in instances_of_b:
  some_list.append(instance.related_instance_of_class_A.some_field_of_class_A)

To get related_instance_of_class_A , i am using ContentType.objects.get_for_model(content_object)要获得related_instance_of_class_A ,我正在使用ContentType.objects.get_for_model(content_object)

Is there any way to use select_related/prefetch related in this case?在这种情况下,有什么方法可以使用 select_related/prefetch 相关的吗?

Couldn't find the exact solution using select_related/ prefetch_related.使用 select_related/prefetch_related 找不到确切的解决方案。 Since my queryset for instances_of_class_b is not so large, reduced the queries this way.由于我的instances_of_class_b查询集不是那么大,因此以这种方式减少了查询。

ids_of_instances_of_b = B.objects.values_list('id', flat=True)
related_instances_of_a = A.objects.filter(object_id__in=ids_of_instances_of_b)

Now, whenever i need to loop over instances of B, no sql query needs to be fired.现在,每当我需要循环 B 的实例时,都不需要触发 sql 查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM