flask-sqlalchemy 一对多关系

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

# 用户表
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(32), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False)
    nickname = db.Column(db.String(32))
    age = db.Column(db.Integer)
    sex = db.Column(db.Integer)

    def __repr__(self):
        return '' % self.useranme

# 文章分组表
class Group(db.Model):
    # 设置表名
    __tablename__ = 'group'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(32), nullable=False, unique=True)

    def __repr__(self):
        return '' % self.name

# 文章表
class Article(db.Model):
    # 设置表名
    __tablename__ = 'article'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(32), nullable=False)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, nullable=False)
    update_time = db.Column(db.DateTime)
    gid = db.Column(db.Integer, db.ForeignKey("group.id"))
    uid = db.Column(db.Integer, db.ForeignKey("user.id"))

    # relationship定义后可以直接使用group字段访问group对象
    # backref 反向引用,会自动在Groups对象里创建一个 articles 字段, 通过articles字段可访问到组id对应的所有article
    group = db.relationship("Group", backref=db.backref("articles"))
    user = db.relationship("User", backref=db.backref("users"))

    def __repr__(self):
        return '
' % self.title

你可能感兴趣的:(flask-sqlalchemy 一对多关系)