flask-sqlalchemy 一对多操作示例

3天前 12次点击 来自 Flask

Step1 生成app与db实例

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///d:\\tmp\\test.db'
db = SQLAlchemy(app)

Step2 定义模型

class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)
    children = db.relationship("Child", backref="parent")

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "parent's name :{}".format(self.name)


class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "child's name :{}".format(self.name)

Step3 写入数据

if __name__ == '__main__':
    db.drop_all()
    db.create_all()
    p1 = Parent('p1')
    c1 = Child('c1')
    c2 = Child('c2')
    p1.children = [c1, c2]
    db.session.add(p1)
    db.session.commit()

    # query
    children = Child.query.all()
    print(children)

    # query & update
    parent = Parent.query.get(1)
    parent.name = 'papa'
    db.session.commit()
    print(parent)

    # delete
    db.session.delete(children[0])
    db.session.commit()
    print(parent.children)

    # fliter
    c = Child.query.filter(Child.name == 'c2').first()
    print(c)
    print(c.parent)

输出:

[child's name :c1, child's name :c2]
parent's name :papa
[child's name :c2]
child's name :c2
parent's name :papa
Card image cap
开发者雷

尘世间一个小小的开发者,每天增加一些无聊的知识,就不会无聊了

要加油~~~

技术文档 >> 系列应用 >>
热推应用
Let'sLearnSwift
学习Swift的入门教程
PyPie
Python is as good as Pie
标签