db.create_all()

It is actually create the tables in our database for all the models that we have declared using db.model. In order to do this, we will need to use a new method called db.create_all.

db.create_all detects models for us and creates tables for them, if those tables do not exist. If those tables do exist, then db.create_all doesn’t do anything for us.

If we call db.create_all multiple times, we won’t be repeatedly creating those same tables.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username@localhost:5432/example'
db = SQLAlchemy(app)

# The Person class inherit from db.Model, we wound up linking and connecting to SQLAlchemy's mappings between classes and tables.
class Person(db.Model):
    # By defult, SQLAlchemy will pick the name of the table for you and set it equal to the lowercase version of your class.
    # But if you want to control the name of the table, you can do this way
    __tablename__ = 'persons'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), nullable=False)

db.create_all()

@app.route('/')
def index():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

通过运行上面的代码,就可以得到:
请添加图片描述


SQLAlchemy Auto-incrementing
请添加图片描述

猜你喜欢

转载自blog.csdn.net/BSCHN123/article/details/121242537
ALL
DB