TypeError:“method”对象不是iterable MySQL

2024-05-29 09:34:37 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图从MySQL表中获取数据并将其分配给queryset时,我得到一个TypeError,使用DjangoModelViewSet中的代码

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

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

^{pr2}$

Tags: 代码selfidcitycloserequestdefconnect
1条回答
网友
1楼 · 发布于 2024-05-29 09:34:37

如果您使用的是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.

在上面的例子中,我还使用了^{}来确保即使视图中有异常,连接也是关闭的,然后使用连接作为上下文管理器生成游标,然后使用光标来确保它也被关闭。在

如果您有一个实际的模型,那么就使用Django ORM,不要自己创建直接连接。你使用的是一台集成度很好的大型机器,而忽略了95%的机器。您不会得到连接池、事务管理、分页等,在这种情况下只需使用适当的查询集和模型视图。在

相关问题 更多 >

    热门问题