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

Django API报错:'Request'对象无'order_data'属性,求排查解决

问题原因分析

这个错误的根源非常明确:你错误地将局部变量的属性当成了request对象的属性。

在你的代码里,order_data和order_detail_data是你在get方法内部定义的局部变量,它们只存在于当前函数的作用域中;而request是Django REST Framework的Request实例,本身并不自带order_data或order_detail_data这些属性,所以当你尝试调用request.order_data和request.order_detail_data时,Python必然会抛出AttributeError。

另外,你的代码还有两个隐性逻辑问题:

  • 在with conn.cursor(...)代码块里,你执行完查询后直接return Response(...)了,这会导致后面的totalData.append(...)和第二个return永远不会被执行,属于无效代码。
  • 既然你是在APIView的get方法中,这个方法本身就只会处理GET请求,所以if request.method == 'GET':这个判断完全多余。
解决方法

针对以上问题,我们可以分两步修正:

1. 修正属性访问错误

直接使用你定义的局部变量order_data和order_detail_data,而不是去request对象上查找。如果只是想调试打印结果,直接打印变量本身即可。

2. 修正代码逻辑

移除多余的request.method判断,调整return的位置,确保逻辑通顺。

修改后的完整代码

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# 假设你的connection()和MySQLdb已正确导入

class Order_ListAPIView(APIView):
    def get(self, request, format=None):
        totalData = []
        cur, conn = connection()
        order_query = ''' SELECT * FROM orders'''
        order_detail_query = ''' SELECT * FROM order_details'''
        
        with conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
            # 查询订单主数据
            cursor.execute(order_query)
            order_result = cursor.fetchall()
            order_data = list(order_result)
            # 直接打印局部变量,而非request的属性
            print(order_data)
            
            # 查询订单详情数据
            cursor.execute(order_detail_query)
            order_detail_result = cursor.fetchall()
            order_detail_data = list(order_detail_result)
            # 同样直接打印局部变量
            print(order_detail_data)
        
        # 整理数据后统一返回
        totalData.append({"order_data": order_data, "order_detail_data": order_detail_data})
        return Response({"totalData": totalData}, status=status.HTTP_200_OK)

额外优化建议

  • 建议使用Django ORM来操作数据库,而非直接编写原生SQL,这样更安全也更符合DRF的开发规范。
  • 注意数据库连接的关闭:虽然with语句会自动关闭cursor,但conn也需要确保关闭,你可以在最后加上conn.close(),或者用上下文管理器来管理数据库连接生命周期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:44:10