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')
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论