pythonflasksqlalchemyjsonify

Python Flask Type Error when returning SQLAlchemy query result


I run a query to populate a on a web form. The is working. I click submit, which should POST the selection back to Flask, which runs a query on it. I am getting TypeError: Object of type BaseQuery is not JSON serializable.

This part seems to work fine until I click "submit":

<form RoomSelectForm action = "#" method = "post">
        <p><label>Select Room</label>
        <select name="roomselect">
            {% for room in roomselect %}
                <option value="{{ room[0] }}">{{ room[0] }}</option>
            {% endfor %}
        </select>
    <input type ="submit" value ="Edit Room" onclick="toggleform()"></p>
</form>

I think the issue is happening with this SQLAlchemy query:

@app.route("/editroom", methods=["POST"])
def edit_room_original_values():
    rm = request.form['roomselect']
    rmval = Roomtable.query.filter(Roomtable.room == rm)
    return dict(value=rmval)

This is the error:

TypeError
TypeError: Object of type BaseQuery is not JSON serializable

Traceback (most recent call last)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1968, in finalize_request
response = self.make_response(rv)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2112, in make_response
rv = jsonify(rv)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 370, in jsonify
dumps(data, indent=indent, separators=separators) + "\n",
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\json\encoder.py", line 201, in encode
chunks = list(chunks)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\json\encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\Lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type BaseQuery is not JSON serializable
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

Solution

  • rmval = Roomtable.query.filter(Roomtable.room == rm)
    

    In this line Roomtable.query.filter() returns a BaseQuery object. You would want to use first() (which would then return a Roomtable object) to get the first query result.

    Try this

    rmval = Roomtable.query.filter(Roomtable.room == rm).first()