Reputation: 339
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
Reputation: 154
Your model reference to your database table by default, but there are some conditions.
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.
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