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

Django DetailView重写get后无法访问context_object_name该如何重构

问题原因

你重写了DetailView的get()方法后,完全抛弃了视图默认的上下文生成逻辑,自定义的上下文仅包含你手动写入的两个变量,所以模板无法获取到默认的object和你定义的profile_detail变量。

重构方案

不需要从头实现View类,Django的通用类视图专门提供了get_context_data()方法用于扩展自定义上下文,符合官方最佳实践,重构后的代码如下:

class UserProfileDetailView(DetailView):
    model = CustomUser
    context_object_name = 'profile_detail'
    template_name = 'user_profile_templates/profile_detail.html'

    def get_context_data(self, **kwargs):
        # 调用父类方法获取默认上下文,已包含object、profile_detail变量
        context = super().get_context_data(**kwargs)
        # 获取当前被查看的用户实例
        viewed_user = self.object
        # 判断当前登录用户是否关注了被查看的用户
        is_following = self.request.user.motivators.filter(id=viewed_user.id).exists()
        # 统计被查看用户的粉丝数
        number_of_followers = viewed_user.motivators.count()
        
        # 追加自定义变量到上下文
        context['is_following'] = is_following
        context['number_of_followers'] = number_of_followers
        return context

补充优化说明

原来的业务逻辑也做了两点性能优化:

  • 用查询集的exists()方法替代循环遍历判断是否存在,避免加载全量关注列表到内存
  • 用查询集的count()方法替代len()统计数量,直接执行SQL的count统计,性能提升明显

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:15:05