Anda harus meletakkan kelas model Anda sebelum create_all()
panggilan, seperti ini:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:[email protected]/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', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
Jika model Anda dideklarasikan dalam modul terpisah, impor sebelum memanggil create_all()
.
Katakanlah, User
model ada dalam file bernama models.py
,
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:[email protected]/flask_app'
db = SQLAlchemy(app)
# See important note below
from models import User
db.create_all()
db.session.commit()
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
Catatan penting: Penting bagi Anda untuk mengimpor model Anda setelah menginisialisasi db
objek sejak, di models.py
. Anda _Anda juga perlu mengimpor db
objek dari modul ini.