Django:如何为模型实例预取相关信息。也许通过包装在一个查询集中? [英] Django: How to prefetch related for a model instance. Perhaps by wrapping in a queryset?
问题描述
我使用Django rest框架,并且在模型关系中具有不错的嵌套。
I use Django rest framework and I have decent nesting in my model relations.
我正在优化查询。我的许多函数都使用或操纵一个模型实例,并且它通常位于数据流的更下游,因此我需要进行一些预取。一个典型的例子是DRF串行器。这是一个示例。
I'm working on optimizing my queries. Many of my functions consume or manipulate a single instance of model and it's often further downstream in the data flow that it turns out I need some prefetching. One classic instance of this is with DRF serializers. Here's an example.
@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
传递查询集尽管我无法完全了解它的工作方式(我只发现了几个地方对此进行了部分讨论,但可能会对此提出其他问题)。
I've seen some solutions suggesting passing queryset with prefetch_related
in the context although I haven't been able to get a full picture on how that would work (I've only found a couple of places that discuss it partially, might open a whole other question on that).
一个简单的解决方法(可能会超出序列化程序):如果我可以使用包装函数将实例包装到查询集中,然后调用prefetch并将其传递给序列化程序
类似的东西
def queryset_wrap(instance):
return type(instance).objects.filter(id=instance.id)
我想知道是否有更好的方法可以做到这一点。 / strong>
I'm wondering if there's a better way to do this.
推荐答案
我自己尚未使用此功能,但我相信它是在Django 1.10中引入的prefetch_related_objects()
函数
I haven't yet used this myself, but I believe that it is the prefetch_related_objects()
function that you are looking for, introduced in Django 1.10
从文档中:
预取给定在可迭代的模型实例上进行查找。这在接收模型实例列表而不是QuerySet的代码中很有用;例如,当从缓存中获取模型或手动实例化模型时。
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.
传递可迭代的模型实例(必须全部属于同一类)以及要预取的查找或Prefetch对象对于。例如:
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')
由于它需要迭代,因此可以将实例包装在列表中:
Since it takes an iterable, you can wrap your instance in a list:
prefetch_related_objects([profile], "relevant_attribute_1", "relevant_attribute_2")
这篇关于Django:如何为模型实例预取相关信息。也许通过包装在一个查询集中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!