Leo S
Leo S

Reputation: 339

Understanding flask_sqlalchemy model

I have postgresql database end it has tables and datum. I want to code a flask app and sqlalchemy to create an app. But I do not understand that when i create a model to use it in sqlAlchemy. Does the created model reference my db table or delete it and create new one?

For example here is a model for my users table for sqlAlchemy:

class Users(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))
    name = db.Column(db.String(1000))

Does it automatically reference my user table in my db or create new one?

Also here is my init.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

db = SQLAlchemy()


def create_app():
    app = Flask(__name__)

    app.config['SECRET_KEY'] = 'thisismysecretkeydonotstealit'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:pswd@localhost/test'

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from .models import Users

    @login_manager.user_loader
    def load_user(user_id):
        return Users.query.get(int(user_id))

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app

Upvotes: 0

Views: 70

Answers (1)

Puneet Jain
Puneet Jain

Reputation: 154

Your model reference to your database table by default, but there are some conditions.

  1. In your db and model class table name must be same. For example if table name in your db is 'user' and class name of your model is Users, then it throws table not found error because sqlalchemy assumes your model refer to 'users'(simply lower case of model class name). Solution is you can explicit assign tablename in your model to match the name in database. Like
class Users(UserMixin, db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(1000))

By __tablename__ you can assign a table name in your model class.

  1. Attribute in model class must match with database column else you got error Unknown column or any other error. So create your model attribute same as your table column with same of column and attribute(case sensitive)

If you want to create or delete a table you can do with db.create_all() and db.drop_all()

Upvotes: 1

Related Questions