Vinz29 Vinz29 - 4 years ago 860
Python Question

Flask: Peewee model_to_dict helper not working

i'm developing a little app for a University project and i need to json encode the result of a query to pass it to a js library, i've read elsewhere that i can use model_to_dict to accomplish that, but i'm getting this error


AttributeError: 'SelectQuery' object has no attribute '_meta'


and i don't know why or what to do, does anyone know how to solve that?

I'm using python 2.7 and the last version of peewee

@app.route('/ormt')
def orm():
doitch = Player.select().join(Nationality).where(Nationality.nation % 'Germany')
return model_to_dict(doitch)

Answer Source

This is because doitch is a SelectQuery instance it is not model, you have to call get()

from flask import jsonify

@app.route('/ormt')
def orm():
    doitch = Player.select().join(Nationality).where(Nationality.nation % 'Germany')
    return jsonify(model_to_dict(doitch.get()))

Also you could use dicts method to get data as dict. This omits creation a whole model stuff.

from flask import jsonify

@app.route('/ormt')
def orm():
    doitch = Player.select().join(Nationality).where(Nationality.nation % 'Germany')
    return jsonify(doitch.dicts().get())

edit

As @lord63 pointed out, you cannot simply return dict, it must be a Flask response so convert it to jsonify.

edit 2

@app.route('/ormt')
def orm():
    doitch = Player.select().join(Nationality).where(Nationality.nation % 'Germany')
    # another query
    sth = Something.select()
    return jsonify(
        'doitch': doitch.dicts().get(),
        'something': sth_query.dicts().get()
    )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download