我正在尝试集成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) relation "user" does not exist
我该如何修复它?
from yourapplication import db db.create_all()
? - Syed Habib M__tablename__ = "users"
添加到您的模型中,然后再试一次。 - ajknzhol