我正在尝试将Flask和SQLAlchemy粘合在一起,但运气不佳。我正在关注官方Flask页面上的示例。
使用控制台,我可以创建&检索单个用户和帖子,但不能执行user.posts之类的操作来获取用户帖子。
from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/dbname'
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
def __init__(self, username):
self.username = username
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
user_id = db.Column('user_id', db.Integer, db.ForeignKey('users.id'))
def __init__(self, user_id, name):
self.user_id = user_id
self.name = name
答案 0 :(得分:4)
要获取用户的帖子,您需要在Users
和Posts
之间set up a relationship:
class User:
# ...
posts = relationship(child='Post', backref='user')