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
请添加图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值