zoukankan      html  css  js  c++  java
  • Flask数据库关系

    基础配置

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    
    app = Flask(__name__)
    db = SQLAlchemy(app)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/flask'
    

    一对多

    class Singer(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(70), unique=True)
        songs = db.relationship('Song', backref='singer')
    
    class Song(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(70), unique=True)
        singer_id = db.Column(db.Integer, db.ForeignKey('singer.id'))
    

    多对一(不是必须时还是用与一对多吧)

    比一对多的用法,会少一个从一里访问多的字段。

    class Citizen(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(70), unique=True)
        city_id = db.Column(db.Integer, db.ForeignKey('city.id'))
        city = db.relationship('City')
    
    
    class Country(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(79), unique=True)
        capital = db.relationship('Capital', uselist=False)
    

    一对一

    class Country(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(79), unique=True)
        capital = db.relationship('Capital', uselist=False)
    
    
    class Capital(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(70), unique=True)
        country_id = db.Column(db.Integer, db.ForeignKey('country.id'))
        country = db.relationship('Country'
    

    多对多

    association_table = db.Table(
        'association',
        db.Column('student_id', db.Integer, db.ForeignKey('student.id')),
        db.Column('teacher_id', db.Integer, db.ForeignKey('teacher.id'))
    )
    
    
    class Student(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(70), unique=True)
        grade = db.Column(db.String(20))
        teachers = db.relationship(
            'Teacher', secondary=association_table, backref='students')
    
    
    class Teacher(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(70), unique=True)
        office = db.Column(db.String(20))
    
  • 相关阅读:
    swift textfiled 输入完毕 return 隐藏键盘 方法
    第一篇,仅是为了纪念
    ASP.NET MVC之验证终结者篇
    ASP.NET MVC扩展之HtmlHelper辅助方法
    Java历程-初学篇 Day04选择结构(1)
    Java历程-初学篇 Day03扫描仪与类型转换
    Java历程-初学篇 Day02变量,数据类型和运算符
    Java历程-初学篇 Day01初识java
    简单工厂模式和策略模式理解
    工厂模式和策略模式的区别
  • 原文地址:https://www.cnblogs.com/tmdhhl/p/11408409.html
Copyright © 2011-2022 走看看