python - 类型错误 : 'method' object is not iterable MySQL

标签 python mysql django django-rest-framework

我得到一个TypeError当我尝试从 MySQL 获取数据时表并将其分配给 queryset在 Django ModelViewSet 中使用以下代码

def queryset(self, request):
      conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='password123', db='sakila')
      cur = conn.cursor()
      cur.execute("SELECT  city_id, city, country_id FROM city")
      json.dumps(list(cur))

      cur.close()
      conn.close()

它给了我以下错误

Exception Value: 'method' object is not iterable

我做错了什么?有什么解决办法吗?我有点菜鸟,所以如果你也能解释一下解决方案,那就太好了。

Traceback:

  File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

> File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

> File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

> File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\viewsets.py" in view
  87.             return self.dispatch(request, *args, **kwargs)

> File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\views.py" in dispatch
  466.             response = self.handle_exception(exc)

> File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\views.py" in dispatch
  463.             response = handler(request, *args, **kwargs)

> File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\mixins.py" in list
  48.         return Response(serializer.data)

> File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\serializers.py" in data
  674.         ret = super(ListSerializer, self).data

> File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\serializers.py" in data
  239.                 self._data = self.to_representation(self.instance)

> File "C:\Users\Naila Akbar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\serializers.py" in to_representation
  614.             self.child.to_representation(item) for item in iterable

> Exception Type: TypeError at /cities/

> Exception Value: 'method' object is not iterable

最佳答案

如果您使用 Django REST 框架,那么您需要生成模型实例(数据库结果)或简单的Python原语(内置类型),并且它会为您处理 JSON 序列化。通过抽象出序列化,框架可以实现内容协商,客户端可以选择接收数据的格式。可能是 JSON,但也可能是其他格式。我怀疑返回 JSON 字符串会破坏框架所做的假设。

改为在 rest_framework.response.Response 对象中返回光标数据,不要自行序列化:

from rest_framework.response import Response
from contextlib import closing

# ...
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='password123', db='sakila')
with closing(conn), conn as cur:
    with cur:
        cur.execute("SELECT  city_id, city, country_id FROM city")
        return Response(list(cur))

来自Responses section in the API Guide :

REST framework supports HTTP content negotiation by providing a Response class which allows you to return content that can be rendered into multiple content types, depending on the client request.

The Response class subclasses Django's SimpleTemplateResponse. Response objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.

在上面的例子中我还使用了 contextlib.closing()确保连接关闭,即使 View 中存在异常,然后使用该连接作为上下文管理器来生成游标,然后使用游标确保它也关闭。

如果您确实有实际模型,请使用 Django ORM 并且不要自己创建直接连接。您正在使用一台集成良好的大型机器,但在这里忽略了该机器的 95%。您不会获得连接池、事务管理、分页等。在这种情况下,只需使用正确的查询集和模型 View 。

关于python - 类型错误 : 'method' object is not iterable MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36787505/

相关文章:

python gspread将csv导入到特定工作表

python - sqlalchemy 是否可以添加字段级别规则,即两个特定列不能同时为 None?

mysql - M2M 关系还是 2 个 FK?

django - 使用自定义管理器用 django 创建对象的目的是什么?

每次运行时不创建测试数据库的Django单元测试

python - 访问 MIB 对象

php - 是否可以将这些文件上传到 MySQL 数据库?

php - 根据查询字符串判断查询类型

MySQL从多个表中选择条件

python - 在 python (matplotlib) 中绘制矢量场