当向ListAPIView发出请求时,会多次调用get_queryset()方法。它被调用了4次,直到我删除了默认的django模型权限,但现在它仍被调用两次。还有什么可能导致重复呼叫。
class PropertyPledgeList(generics.ListAPIView):
serializer_class = PledgeListSerializer
ordering_fields = ('amount_cents')
def get_queryset(self):
slug = self.kwargs['slug']
return get_object_or_404(Property, slug=slug).pledges.all().prefetch_related("user")
答案 0 :(得分:0)
重复查询是get_object_or_404()
的结果。
如果要从URL关键字参数检索父对象,可以将其设置为调度方法中的属性,该方法仅被调用一次,然后在get_queryset()
中访问已检索的对象。
from rest_framework.exceptions import NotFound
class PropertyPledgeList(generics.ListAPIView):
queryset = PropertyPledge.objects.all()
serializer_class = PledgeListSerializer
def dispatch(self, request, *args, **kwargs):
try:
self.property = Property.objects.get(id=kwargs['slug'])
except Property.DoesNotExist:
self.property = None
return super().dispatch(request, *args, **kwargs)
def get_queryset(self):
if not self.property:
raise NotFound
return self.property.get_pledges()