Skip to content
Advertisement

Flask-SQLAlchemy: ‘Table’ object has no attribute ‘query_by’

I’m developing an API with Flask and I cannot retrieve queries from a MySQL database I’ve connected with flask-sqlalchemy (not sqlalchemy alone). This is a pre-existing database downloaded from my client’s PHPMyAdmin, so I haven’t ran db.create_all(): I simply created the connection string in config.py, then instantiated db = SQLAchemy() and initialized it (db.init_app(app)) in my factory function (i’m using the factory pattern together with blueprints).

I’ve already checked and my computer is running the mysql process, the login credentials provided are correct and the database exists in my computer. I’m using MariaDB because I run Manjaro Linux.

This is the connection string, located in config.py:

SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or "mariadb+mariadbconnector://dev:dev@localhost/desayunos56"

This is the relevant model. It was created using flask-sqlacodegen and then modified by me to only use the relevant columns within the table. At models.py:

from flask_sqlalchemy import SQLAlchemy
from app import db
# coding: utf-8

t_aus_postmeta = db.Table(
    """ 
        post_id: Order ID
        meta_key: Type of value (client name, billing address)
        meta_value: Value of meta_key (Name or address itself)
     """
    'aus_postmeta',
    #db.Column('meta_id', db.BigInteger, nullable=False),
    db.Column('post_id', db.BigInteger, nullable=False, server_default=db.FetchedValue()),
    db.Column('meta_key', db.String(255, 'utf8mb4_unicode_ci')),
    db.Column('meta_value', db.String(collation='utf8mb4_unicode_ci'))
)

And finally, this is the file with the error, views.py. It’s a blueprint already registered to __init__.py. I created it only with the intention of checking if I could run queries, but I don’t really intend to render anything from Flask:

from flask import render_template
from . import main
from .. import db
from app.models import t_aus_postmeta


@main.route("/", methods=["GET"])
def index():
    result = t_aus_postmeta.query_by(post_id=786).first()

This is the error I get: AttributeError: 'Table' object has no attribute 'query_by'

I think it’s noteworthy that, although my linter doesn’t complain due to unresolved imports, when I use t_aus_postmeta I don’t get any method suggestions.

All the questions I’ve checked are based on using sqlalchemy instead of flask-sqlalchemy. What could be causing this error? At this point, I’m at a loss.

Advertisement

Answer

I can’t find the API reference for the “query_by” method you are using. It seems there is no such method. Perhaps you meant “filter_by” instead?

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement