Search code examples
pythonflaskpeeweeflask-peewee

Flask peewee AttributeError: 'ModelSelect' object has no attribute '_meta'


I have a very simple setup, a model and api file in a pipenv flask environment. I'm currently using peewee and been facing an issue with getting all results from a datatable. I've done this before in python and works fine however not sure what in Flask I'm doing wrong. Here is my model

from peewee import * 
import peewee as pw


db = pw.MySQLDatabase('xxxxx', host="localhost", port=3306, user='xxx', 
password="xxxxx")


class HomeCarousel(Model):
   icon = pw.CharField(100)
   header = pw.CharField(50)
   text = pw.CharField(100)
   class Meta:
      database = db

and here is my api file

from flask import Flask, g
from flask import jsonify, make_response
from playhouse.shortcuts import model_to_dict
from peewee import *
import peewee as pw
from models import *
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})

@app.route('/')
def index():
   items = HomeCarousel.select()
   items = model_to_dict(items)
   return items

if __name__ == '__main__':
    app.run()

Now the issue is that when I do items = HomeCarousel.select() I get an error "AttributeError: 'ModelSelect' object has no attribute '_meta'"

If I select only one record, everything works just fine. items = HomeCarousel.get()

Does anyone know what I'm doing wrong here?

Thanks


Solution

  • The model_to_dict expects an object instance. You're passing it a ModelSelect. You need to iterate over the objects returned in your ModelSelect:

    @app.route('/')
    def index():
       items = HomeCarousel.select()
       items = [model_to_dict(item) for item in items]
       return items