SQLAlchemy create_all() does not create tables

前端 未结 1 1077
慢半拍i
慢半拍i 2020-11-27 13:14

I\'m trying to integrate PostgreSQL and SQLAlchemy but SQLAlchemy.create_all() is not creating any tables from my models.

My code:

from flask im         


        
相关标签:
1条回答
  • 2020-11-27 13:45

    You should put your model class before create_all() call, like this:

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
    db = SQLAlchemy(app)
    
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(80), unique=True)
        email = db.Column(db.String(120), unique=True)
    
        def __init__(self, username, email):
            self.username = username
            self.email = email
    
        def __repr__(self):
            return '<User %r>' % self.username
    
    db.create_all()
    db.session.commit()
    
    admin = User('admin', 'admin@example.com')
    guest = User('guest', 'guest@example.com')
    db.session.add(admin)
    db.session.add(guest)
    db.session.commit()
    users = User.query.all()
    print users
    

    If your models are declared in a separate module, import them before calling create_all().

    Say, the User model is in a file called models.py,

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
    db = SQLAlchemy(app)
    
    # See important note below
    from models import User
    
    db.create_all()
    db.session.commit()
    
    admin = User('admin', 'admin@example.com')
    guest = User('guest', 'guest@example.com')
    db.session.add(admin)
    db.session.add(guest)
    db.session.commit()
    users = User.query.all()
    print users
    

    Important note: It is important that you import your models after initializing the db object since, in your models.py _you also need to import the db object from this module.

    0 讨论(0)
提交回复
热议问题