在
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 问题。
我该怎么办?
在 models.py 中编辑非常简单,需要排序。
我删除了
views.py
和 serializers.py
中的所有代码
class B(models.Model):
...
class Meta:
ordering=['-order']