开发者

Basic example of saving & retrieving a relationship in Flask with SQLAlchemy

I'm trying to glue Flask and SQLAlchemy together but with little luck. I'm following the example from the official Flask page.

Using the console, I can create & retrieve individual users and posts, but can't do stuff like user.posts to get the users 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, pr开发者_JAVA技巧imary_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


To get the users' posts, you need to set up a relationship between Users and Posts:

class User:
    # ...
    posts = relationship(child='Post', backref='user')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜