unicorn_crack
unicorn_crack

Reputation: 1099

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, 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

Upvotes: 2

Views: 1381

Answers (1)

David Fraser
David Fraser

Reputation: 7439

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

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

Upvotes: 4

Related Questions