6

Soy nuevo en FlaskAlchemy. Quiero filtrar una consulta SQL sobre los valores de una columna LOC_CODE. Hice db.session.query(schools).filter_by(LOC_CODE='X270').first(). Pero el compilador devuelve:

(base) C:\Users\antoi\Documents\Programming\musicaltroupefinder>python hello_world.py
C:\ProgramData\Anaconda3\lib\site-packages\flask_sqlalchemy\__init__.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
 * Serving Flask app "hello_world" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2019-12-20 13:03:58,460] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1249, in _execute_context
    cursor, statement, parameters, context
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 580, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: no such column: schools.LOC_CODE

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "hello_world.py", line 32, in index
    school = School.query.filter(School.LOC_CODE == 'X270').all()
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 3186, in all
    return list(self)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 3342, in __iter__
    return self._execute_and_instances(context)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 3367, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 988, in execute
    return meth(self, multiparams, params)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 287, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1107, in _execute_clauseelement
    distilled_params,
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1253, in _execute_context
    e, statement, parameters, cursor, context
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1473, in _handle_dbapi_exception
    util.raise_from_cause(sqlalchemy_exception, exc_info)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 398, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 152, in reraise
    raise value.with_traceback(tb)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1249, in _execute_context
    cursor, statement, parameters, context
  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 580, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: schools.LOC_CODE
[SQL: SELECT schools."LOC_CODE" AS "schools_LOC_CODE"
FROM schools
WHERE schools."LOC_CODE" = ?]
[parameters: ('X270',)]
(Background on this error at: http://sqlalche.me/e/e3q8)
127.0.0.1 - - [20/Dec/2019 13:03:58] "[1m[35mGET / HTTP/1.1[0m" 500 -

Aqui esta el entero codigo:

from flask import Flask 
from flask import render_template
from flask_sqlalchemy import SQLAlchemy

from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import mapper, sessionmaker


from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'
db = SQLAlchemy(app)

class School(db.Model):
    __tablename__ = 'schools'
    # __table_args__ = { 'extend_existing': True }
    LOC_CODE = db.Column(db.Text, primary_key=True)   


@app.route("/")
def index():
    school = School.query.filter(School.LOC_CODE == 'X270').first()
    print("School's name is", school.SCHOOLNAME)
    return render_template("index.html")

2 respuestas 2

0

Según el mensaje de error, parece claro que la columna LOC_CODE no existe en la tabla schools de SQLite.

Revisa la creación del modelo de datos para ver el nombre exacto de dicha columna en la tabla schools.

0

¿Estás seguro que la estructura de la tabla se corresponde con tu definición de modelo?

Yo probaría a borrar tu BBDD y volverla a crear para asegurarte.

He adaptado tu código y funciona como era de esperar.

from flask import Flask 
from flask import render_template
from flask_sqlalchemy import SQLAlchemy

from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import mapper, sessionmaker


from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'
db = SQLAlchemy(app)

class School(db.Model):
    __tablename__ = 'schools'
    # __table_args__ = { 'extend_existing': True }
    LOC_CODE = db.Column(db.Text, primary_key=True)   
    SCHOOLNAME = db.Column(db.Text)   

db.create_all()
db.session.commit()

item = School(LOC_CODE='X270', SCHOOLNAME='X270bbbbbb')
db.session.add(item)
db.session.commit()


school = School.query.filter(School.LOC_CODE == 'X270').first()
print("School's name is", school.SCHOOLNAME)

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.