django REST api通用视图的queryset属性 [英] the queryset attribute of django REST api generic views

查看:181
本文介绍了django REST api通用视图的queryset属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解django rest框架的通用API视图,该文档告诉我,虽然覆盖了通用视图的方法,但我不应该访问 queryset 属性直接访问,而是访问 get_queryset()函数,因为显然queryset属性仅被评估一次, get_queryset()做不同的事吗?
queryset属性是否曾经更新过?

I am trying to understand the django rest framework generic API views, the documentation tells me that while overriding methods of the generic views, I shouldn't be accessing the queryset attribute directly and instead access the get_queryset() function because apparently the queryset attribute is evaluated only once, what does the get_queryset() do differently? Does the queryset attribute ever get updated?

推荐答案

要进一步扩展,请源代码会告诉你真相。

To further expand, the source code will tell you the truth.

    assert self.queryset is not None, (
        "'%s' should either include a `queryset` attribute, "
        "or override the `get_queryset()` method."
        % self.__class__.__name__
    )

    queryset = self.queryset
    if isinstance(queryset, QuerySet):
        # Ensure queryset is re-evaluated on each request.
        queryset = queryset.all()
    return queryset




  • 首先检查查询集是否已定义

  • 其次检查指定的查询集是否为Django Queryset类的实例

  • 再次对其进行重新评估(进行数据库查询)查询集并设置结果

  • 第四次返回结果

    • First it checks queryset is defined
    • Second it checks if the queryset specified is an instance of Django's Queryset class
    • Third it re-evaluates (makes a database query) the queryset and sets the results
    • Fourth it returns the results
    • 有关直接使用self.queryset的警告是,对结果进行评估时会缓存结果,因此与使用self.get_queryset()相对,对该值的进一步引用将是最新的。

      The warning about using self.queryset directly is that results are cached when evaluated so further references to this value will not be up to date as opposed of using self.get_queryset().

      这篇关于django REST api通用视图的queryset属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆