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

Django中PortfolioView(ListView)调用MakeGraphs遇Deferred Attribute Error

解决Deferred Attribute Error的问题

你这里踩了两个关键坑,才导致了这个错误:

  • 你直接把模型类的字段(Prospect.psuccess、Prospect.hc_type)传给了MakeGraphs,但这个函数需要的是实际的查询结果数据,不是模型字段本身——模型字段是类属性,不是具体的数据集,自然会触发延迟属性错误。
  • 你的查询语句Prospect.objects.all().filter(owner__username=self.request.user)没有赋值给任何变量,相当于白写了,根本没把当前用户的Prospect数据传递给图表生成函数。

下面是修正后的完整代码,我会逐个解释关键改动:

def get_context_data(self, **kwargs):
    # 1. 先获取当前用户的专属Prospect数据,赋值给变量保存
    # 提示:all()可以省略,filter本身就会返回查询集
    user_prospects = Prospect.objects.filter(owner__username=self.request.user)
    
    # 2. 从查询集中提取图表需要的字段数据
    # 用values_list拿到扁平化的字段值列表,适配MakeGraphs的数据需求
    psuccess_values = user_prospects.values_list('psuccess', flat=True)
    hc_type_values = user_prospects.values_list('hc_type', flat=True)
    
    # 3. 传入实际数据调用MakeGraphs
    graph_context = MakeGraphs(psuccess_values, hc_type_values)
    
    # 4. 正确合并上下文:先拿父类默认上下文,再叠加图表数据
    context = super().get_context_data(**kwargs)
    context.update(graph_context)
    
    return context

核心修正说明:

  1. 锁定用户数据:把查询结果存到user_prospects里,确保后续用的是当前用户的专属数据,而不是模型的空字段属性。
  2. 传递有效数据:用values_list提取字段的实际值集合,让MakeGraphs拿到可直接处理的数据集,这是解决Deferred Attribute Error的关键。
  3. 正确处理上下文:先调用父类方法获取ListView默认的上下文(比如分页数据、列表对象),再用update合并图表生成的上下文——之前直接把graph_context传给super会覆盖默认参数,导致上下文缺失。

如果MakeGraphs的参数要求是查询集本身(而非单独的字段列表),你也可以直接传user_prospects,然后在函数内部处理字段提取:

graph_context = MakeGraphs(user_prospects)

然后在MakeGraphs里用prospects.values_list('psuccess', flat=True)来获取对应数据即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:02:19