You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django REST类视图中@last_modified无法获取self的问题

解决Django REST类视图中last_modified装饰器访问self的问题

你遇到的核心问题是:用@method_decorator装饰类视图的get方法后,last_modified装饰器指定的函数无法直接获取视图实例self。这是因为@method_decorator会将类方法的参数适配为普通函数的参数,此时last_modified_func的第一个参数是request而非视图实例。

解决方案:通过request.view访问视图实例

Django在处理类视图请求时,会给request对象添加一个view属性,这个属性指向当前的视图类实例(也就是你需要的self)。利用这个特性,你可以修改get_last_modified_time函数,通过request.view获取视图实例,进而访问其属性和方法。

修改后的完整代码如下:

from django.views.decorators.http import last_modified  
from django.utils.decorators import method_decorator
from rest_framework import generics

class MyView(generics.ListAPIView):  
    def get_last_modified_time(request, *args, **kwargs):
        # 获取当前视图实例(等价于原代码中的self)
        view_instance = request.view
        # 这里可以调用视图实例的任意方法或属性,比如:
        # queryset = view_instance.get_queryset()
        post = Post.objects.get(pk=kwargs.get('id'))
        return post.date

    @method_decorator(last_modified(last_modified_func=get_last_modified_time))  
    def get(self, request, *args, **kwargs):
        # 你的原有业务逻辑
        return super().get(request, *args, **kwargs)

替代写法:用类装饰器方式

你也可以把@method_decorator直接应用到类上,指定装饰get方法,效果完全一致:

from django.views.decorators.http import last_modified  
from django.utils.decorators import method_decorator
from rest_framework import generics

@method_decorator(last_modified(last_modified_func=MyView.get_last_modified_time), name='get')
class MyView(generics.ListAPIView):  
    def get_last_modified_time(request, *args, **kwargs):
        view_instance = request.view
        post = Post.objects.get(pk=kwargs.get('id'))
        return post.date

    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)

为什么不能直接移除@method_decorator?

移除@method_decorator后,last_modified装饰器会直接作用于类的get方法,此时装饰器会把视图实例self当作第一个参数传入get_last_modified_time,但last_modified装饰器期望第一个参数是request,这就导致了你遇到的错误。所以必须保留@method_decorator来完成参数适配。

内容的提问来源于stack exchange,提问作者user19315471

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 01:55:24