我使用 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 中引入
Prefetches the given lookups on an iterable of model instances. This is useful in code that receives a list of model instances as opposed to a QuerySet; for example, when fetching models from a cache or instantiating them manually.
Pass an iterable of model instances (must all be of the same class) and the lookups or Prefetch objects you want to prefetch for. For example:
>>> 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/