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

Django开发报错:AttributeError: type object 'Services' has no attribute 'app'

解决Django中调用类方法时的AttributeError: type object 'Services' has no attribute 'app'问题

错误原因

你在views.py中直接通过类Services调用实例方法find_node_type,还手动传入Services作为第一个参数,这种用法完全错误:

  • 实例方法find_node_type依赖类实例的self.app属性,而self.app是在类的__init__方法中初始化的
  • 直接通过类调用实例方法时,__init__不会被执行,自然不存在app属性,因此抛出AttributeError

解决方案

必须先创建Services类的实例,再通过实例调用find_node_type方法,Python会自动将实例作为self参数传入方法。

修正后的views.py代码:

from django.shortcuts import render
from BitirmeTeziSourceCode.queryOnMetadataModel import Services

# Create your views here.
def home(request):
    # 创建Services类的实例,此时__init__方法执行,初始化self.app
    service = Services()
    # 调用实例方法,无需手动传递self参数
    data = service.find_node_type('Region')
    
    nodes = {
        "nodes" : data
    }
    
    return render(request , "index.html" , nodes)

补充说明

  • 实例方法的第一个参数self代表类的实例,Python会自动传递,不需要手动传入
  • 如果业务场景需要不创建实例就调用方法,可以考虑将方法改为类方法(用@classmethod装饰)或静态方法(用@staticmethod装饰),但此场景下因为需要使用实例化的App连接,所以必须用实例方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:26:14