python - SQLAlchemy create_all() 不创建表

标签 python postgresql sqlalchemy flask-sqlalchemy

我正在尝试集成 PostgreSQL 和 SQLAlchemy,但 SQLAlchemy.create_all() 没有从我的模型创建任何表。

我的代码:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
db.create_all()
db.session.commit()

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

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        

但我收到此错误:sqlalchemy.exc.ProgrammingError: (ProgrammingError) 关系“用户”不存在

我该如何解决这个问题?

最佳答案

您应该将模型类放在 create_all() 调用之前,如下所示:

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

with app.app_context():
    db.create_all()

    db.session.add(User('admin', 'admin@example.com'))
    db.session.add(User('guest', 'guest@example.com'))
    db.session.commit()

    users = User.query.all()
    print(users)

如果您的模型在单独的模块中声明,请在调用 create_all() 之前导入它们。

比如说,User 模型在一个名为 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

with app.app_context():
    db.create_all()

    db.session.add(User('admin', 'admin@example.com'))
    db.session.add(User('guest', 'guest@example.com'))
    db.session.commit()
    
    users = User.query.all()
    print(users)

重要提示:在初始化 db 对象后导入模型很重要,因为在 models.py 中您还需要从这个模块导入 db 对象。

关于python - SQLAlchemy create_all() 不创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20744277/

相关文章:

python - 从键、值元组列表创建字典,同时维护重复键

postgresql - 在 Ubuntu 中打开端口

python - Matplotlib-Venn 中准确的颜色混合

python - 在python中获取类中的所有常量

python - 正则表达式表情符号Unicode

postgresql - 如何使用多个 where _or 创建 hasura graphql 查询?

PostgreSQL 9.5 : Skip first two lines in the text file

python-3.x - psycopg2 在 "$body$"处或附近抛出未终止的美元引用字符串错误

python - Pyramid :sqlalchemy.exc.OperationalError

python - 如何在 SQLAlchemy 中组合两个模型类