如何在 Django 中使用 order_by 解决 N+1 双重 prefetch_lated 问题?

问题描述 投票:0回答:1

models.py
中,简单的结构是...

Model A(parent of B) <- Model B(parent of C) <- Model C

在views.py中,我想在B,C中使用

prefetch_related
,在b中使用
order_by

a_obj = A.objects.prefetch_related(Prefetch("b__c", queryset=B.objects.all().order_by("-order")))

但是在

serializers.py
中,我无法访问c的数据。

def get_data(self, group):
   for b in group.b.all():
      print(b.c.all())  # ===> result: queryset [B object(pk)]

我还尝试了另一种方式

views.py
serializers.py

# views.py
a_obj = A.objects.prefetch_related("b__c")

# serializers.py
def get_data(self, group):
   for b in group.b.all().order_by("-order"):
      print(b.c.all())  # ===> N+1 query occurred

但我有 N+1 问题。

我该怎么办?

django django-rest-framework
1个回答
0
投票

在 models.py 中编辑非常简单,需要排序。

我删除了

views.py
serializers.py

中的所有代码
class B(models.Model):
   ...
   class Meta:
      ordering=['-order']
© www.soinside.com 2019 - 2024. All rights reserved.