Flask-SQLAlchemy資料庫操作
阿新 • • 發佈:2018-11-05
建表
# -*- coding: UTF-8 -*- from . import db #多對多關係表,兩組一對多,即為多對多 class Boy2Girl(db.Model): __tablename__ = 'boy2girl' nid = db.Column(db.Integer,primary_key=True) #建立一對多關係,ForeignKey傳入對應表的__tablename__.id boy_id = db.Column(db.Integer,db.ForeignKey('boy.id')) # 建立一對多關係,ForeignKey傳入對應表的__tablename__.id girl_id = db.Column(db.Integer,db.ForeignKey('girl.id')) class Boy(db.Model): __tablename__ = 'boy' id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(32),unique=True) age = db.Column(db.Integer) #並不會在資料庫中生成列,作用為ORM呼叫時可以通過.來呼叫另一張表 #例如boy.girl,girl.boy #傳入的引數為另一張表的類名,關係表的表名,反向查詢時的名字,可以為任意名字 girl = db.relationship('Girl',secondary = Boy2Girl.__tablename__,backref = 'boy') car = db.relationship('Car',backref = 'boy') def __repr__(self): return '<Boy %r>'%self.name class Girl(db.Model): __tablename__ = 'girl' id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(32),unique=True) age = db.Column(db.Integer) def __repr__(self): return '<Girl %r>' % self.name class Car(db.Model): __tablename__ = 'car' id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(32),unique=True) #建立一對多關係,ForeignKey傳入對應表的__tablename__.id,寫在多的一對多中多的那邊 boy_id = db.Column(db.Integer,db.ForeignKey('boy.id')) def __repr__(self): return '<Car %r>'%self.name