我使用Django rest框架,并且在模型关系中具有不错的嵌套。
我正在优化查询。我的许多函数都使用或操作一个模型实例,并且它通常位于数据流的更下游,因此我需要进行一些预取。一个典型的例子是DRF串行器。这是一个例子。
@api_view(['GET'])
def fetch_user_profile(request):
profile = request.user.profile # has many nested relationships
return Response(UserProfileSerializer(profile).data, status=status.HTTP_200_OK) # this ends up taking many queries
我没有看到一些解决方案,建议在上下文中使用
prefetch_related
传递查询集,尽管我无法全面了解它的工作方式(我只发现了几个部分讨论它的地方,可能会打开一个完整的其他问题)。一个简单的解决方法(并且将在序列化程序之外进行推广)是,如果我可以使用包装函数将实例包装到查询集中,然后对其进行预取,然后将其传递给序列化程序。
就像是:
def queryset_wrap(instance):
return type(instance).objects.filter(id=instance.id)
我想知道是否有更好的方法可以做到这一点。
最佳答案
我尚未亲自使用过此功能,但我相信它是您要查找的prefetch_related_objects()
函数,是Django 1.10中引入的
From the docs:
在可迭代的模型实例上预取给定的查找。这在接收模型实例列表而不是QuerySet的代码中很有用;例如,从缓存中获取模型或手动实例化模型时。
传递可迭代的模型实例(必须全部属于同一类),并传递要为其预取的查找或Prefetch对象。例如:
>>> from django.db.models import prefetch_related_objects
>>> restaurants = fetch_top_restaurants_from_cache() # A list of Restaurants
>>> prefetch_related_objects(restaurants, 'pizzas__toppings')
由于它需要迭代,因此可以将实例包装在列表中:
prefetch_related_objects([profile], "relevant_attribute_1", "relevant_attribute_2")
关于python - Django:如何为模型实例预取相关信息。也许通过包装在一个查询集中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54759975/