2014-11-07 55 views
0

我想返回查詢的結果爲JSON。我正在使用以下路線將一個模型實例作爲JSON對象返回。如何以JSON的形式返回結果列表?

@mod.route('/autocomplete/<term>', methods=['GET']) 
def autocomplete(term): 

    country = Country.query.filter(Country.name_pt.ilike('%'+ term + '%')).first() 

    country_dict = country.__dict__ 
    country_dict.pop('_sa_instance_state', None) 

    return jsonify(json_list=country_dict) 

此代碼工作得很好,如果我使用first()方法。但是,我需要使用all()來獲取所有結果。當我這樣做時,我得到以下錯誤。

country_dict = country.__dict__ 
AttributeError: 'list' object has no attribute '__dict__' 

我應該怎麼做才能將整個結果列表作爲JSON返回?

回答

5

您需要爲列表中的每個項目執行「jsonify準備步驟」,因爲.all()返回模型實例列表,而不僅僅是像.first()這樣的一個實例。在每個__dict__的副本上工作,以免混淆SQLAlchemy的實例內部表示。

@mod.route('/autocomplete/<term>', methods=['GET']) 
def autocomplete(term): 
    countries = [] 

    for country in Country.query.filter(Country.name_pt.ilike('%' + term + '%'): 
     country_dict = country.__dict__.copy() 
     country_dict.pop('_sa_instance_state', None) 
     countries.append(country_dict) 

    return jsonify(json_list=countries) 

也許只是爲了更好地將數據返回關於每個國家的明確,而不是試圖神奇jsonify實例。

@mod.route('/autocomplete/<term>', methods=['GET']) 
def autocomplete(term): 
    countries = [] 

    for country in Country.query.filter(Country.name_pt.ilike('%' + term + '%'): 
     countries.append({ 
      'id': country.id, 
      'name': country.name_pt, 
     }) 

    return jsonify(countries=countries)