Do you still need to create SQLAlchemy models if the DB already exists?

Viewed 62

New to Flask and SQL - teaching myself to build a fairly basic web app.

The lessons that I have followed so far haven't made it clear to me how a pre-existing SQLite database interacts with SQLAlchemy.

I have created an SQLite database using SQL in my terminal which already has the tables set up that I want to use.

I am now looking to connect it to my Flask app using SQLAlchemy. For examples sake lets say this is the model of a Book table in my DB has the following SQL setup:

CREATE TABLE "Book" (
    "isbn"  INTEGER NOT NULL,
    "title" TEXT NOT NULL,
    "author"    TEXT NOT NULL,
    PRIMARY KEY("id" AUTOINCREMENT)
)

Is the purpose of outlining the model in the Flask app like below just so that the application knows how to interact with the DB?

class Book(db.Model):
    isbn = db.column(db.Integer, primary_key = True)
    title = db.column(db.String(50), unique = False, index = True)
    author = db.column(db.String(50), unique = True, index = True)

And given the double up in almost all of the information that is presented - is there a more efficient way to import a model like this from a database that is already set up?

1 Answers

You add new line tablename, old topic here Document

class Book(db.Model):
     __tablename__ = 'Book'
    isbn = db.column(db.Integer, primary_key = True)
    title = db.column(db.String(50), unique = False, index = True)
    author = db.column(db.String(50), unique = True, index = True)
Related