【问题标题】:Django: How to prefetch related for a model instance. Perhaps by wrapping in a queryset?Django:如何预取模型实例的相关信息。也许通过包装查询集?
【发布时间】:2019-07-12 14:04:40
【问题描述】:

我使用 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)

我想知道是否有更好的方法来做到这一点。

【问题讨论】:

    标签: python django django-rest-framework query-optimization


    【解决方案1】:

    我自己还没有使用过这个,但我相信它是你正在寻找的 prefetch_related_objects() 函数,在 Django 1.10 中引入

    From the docs:

    在可迭代的模型实例上预取给定的查找。这在接收模型实例列表而不是 QuerySet 的代码中很有用;例如,从缓存中获取模型或手动实例化它们时。

    传递一个可迭代的模型实例(必须都属于同一个类)和要预取的查找或预取对象。例如:

    >>> 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 2018-11-21
      • 2020-11-24
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多