2014-11-07 51 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)