[Fixed]-TypeError: 'method' object is not iterable MySQL

1👍

If you are using the Django REST framework, then you are expected to produce model instances (database results) or simple Python primitives (built-in types), and it’ll take care of serialisation to JSON for you. By abstracting away the serialization, the framework can implement content-negotiation, where the client can pick what format they receive the data in. That could be JSON, but it could also be something else. I suspect that returning a JSON string is going to upset the assumptions the framework makes.

Return your cursor data in a rest_framework.response.Response object instead, do not serialize this yourself:

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))

From the 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.

In the above example I also used contextlib.closing() to ensure the connection is closed even if there are exceptions in the view, and then used the connection as a context manager to produce the cursor, and then the cursor to ensure it too is closed.

If you do have an an actual model, then use the Django ORM and don’t create direct connections yourself. You are using a big, well-integrated machine and are ignoring 95% of that machine here. You won’t get connection pooling, transaction management, pagination, etc. etc. etc. Just use proper querysets and model views in that case.

Leave a comment