Flask-SQLAlchemy(MySQL)之一對多、一對一、多對多關(guān)系

一對多

  1. 創(chuàng)建兩個(gè)模型
class Person(db.Model):
    __tablename__ = 'person'
    name = db.Column(db.String(20), primary_key=True)
    age = db.Column(db.Integer)
    birth = db.Column(db.Date)
    phone = db.Column(db.String(11), unique=True)

    # 使用關(guān)系函數(shù)定義關(guān)系屬性
    cars = db.relationship('Car')

    def __repr__(self):
        return '姓名:{name} 年齡:{age} 生日:{birth} 電話:{phone}'.format(name=self.name, age=self.age, birth=self.birth,
                                                                 phone=self.phone)


class Car(db.Model):
    name = db.Column(db.String(10), primary_key=True)
    price = db.Column(db.Float)
    # 定義外鍵(表明.字段名)
    course_phone = db.Column(db.String(11), db.ForeignKey('person.phone'))

    def __repr__(self):
        return '汽車類型:{name} 總價(jià):{price}'.format(name=self.name, price=self.price)
  1. 通過設(shè)置外鍵建立關(guān)系
@app.cli.command()
def insertpc():
    person = Person(name='老趙', age=27, birth=datetime.datetime.now(), phone='17777777777')
    car1 = Car(name='五菱宏光', price=55000.00, course_phone='17777777777')
    car2 = Car(name='吉利自由艦', price=43000.00, course_phone='17777777777')
    db.session.add(person)
    db.session.add(car1)
    db.session.add(car2)
    db.session.commit()
    click.echo('insert')

或者通過關(guān)系屬性cars調(diào)用append建立關(guān)系

@app.cli.command()
def insertpc():
    person = Person(name='老趙', age=27, birth=datetime.datetime.now(), phone='17777777777')
    car1 = Car(name='五菱宏光', price=55000.00)
    car2 = Car(name='吉利自由艦', price=43000.00)
    db.session.add(person)
    person.cars.append(car1)
    person.cars.append(car2)
    db.session.commit()
    click.echo('insert')

通過remove解綁關(guān)系

person.cars.remove(car1)
db.session.commit()
  1. 查詢
@app.cli.command()
def querypc():
    person = Person.query.first()
    click.echo(person.cars)

查詢結(jié)果如下:

[汽車類型:五菱宏光 總價(jià):55000.0, 汽車類型:吉利自由艦 總價(jià):43000.0]

建立雙向關(guān)系

  1. 創(chuàng)建兩個(gè)模型
class Person(db.Model):
    __tablename__ = 'person'
    name = db.Column(db.String(20), primary_key=True)
    age = db.Column(db.Integer)
    birth = db.Column(db.Date)
    phone = db.Column(db.String(11), unique=True)

    # 使用關(guān)系函數(shù)定義關(guān)系屬性
    cars = db.relationship('Car', back_populates='person')

    def __repr__(self):
        return '姓名:{name} 年齡:{age} 生日:{birth} 電話:{phone}'.format(name=self.name, age=self.age, birth=self.birth,
                                                                 phone=self.phone)


class Car(db.Model):
    name = db.Column(db.String(10), primary_key=True)
    price = db.Column(db.Float)
    # 定義外鍵(表明.字段名)
    course_phone = db.Column(db.String(11), db.ForeignKey('person.phone'))

    person = db.relationship('Person', back_populates='cars')

    def __repr__(self):
        return '汽車類型:{name} 總價(jià):{price}'.format(name=self.name, price=self.price)
  1. 建立關(guān)系
@app.cli.command()
def insertpc():
    person = Person(name='老趙', age=27, birth=datetime.datetime.now(), phone='17777777777')
    car1 = Car(name='五菱宏光', price=55000.00)
    car2 = Car(name='吉利自由艦', price=43000.00)
    db.session.add(person)
    person.cars.append(car1)
    person.cars.append(car2)
    db.session.commit()
    click.echo('insert')
  1. 查詢
@app.cli.command()
def queryc():
    car = Car.query.first()
    click.echo('{person} {car} '.format(person=car.person, car=car))

查詢結(jié)果如下:

姓名:老趙 年齡:27 生日:2018-10-24 電話:17777777777 汽車類型:五菱宏光 總價(jià):55000.0

一對一關(guān)系

  1. 創(chuàng)建兩個(gè)模型,注意:創(chuàng)建一對一關(guān)系是通過將uselist設(shè)為False
class Husband(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(10))
    age = db.Column(db.Integer)

    wife = db.relationship('Wife', uselist=False)

    def __repr__(self):
        return '老公:{name} 年齡:{age}'.format(name=self.name, age=self.age)


class Wife(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(10))
    age = db.Column(db.Integer)
    husband_id = db.Column(db.Integer, db.ForeignKey('husband.id'))

    husband = db.relationship('Husband')

    def __repr__(self):
        return '老婆:{name} 年齡:{age}'.format(name=self.name, age=self.age)
  1. 建立關(guān)系,注意:一對一關(guān)系不能使用append,因?yàn)槭菃蝹€(gè)記錄,所以使用=
@app.cli.command()
def inserthw():
    husband = Husband(name='老王', age=24)
    wife = Wife(name='小紅', age=18)
    db.session.add(husband)
    husband.wife = wife
    db.session.commit()
    click.echo('insert')
  1. 查詢
@app.cli.command()
def queryhw():
    husband = Husband.query.first()
    click.echo('{husband} {wife}'.format(husband=husband, wife=husband.wife))

查詢結(jié)果如下:

老公:老王 年齡:24 老婆:小紅 年齡:18

多對多關(guān)系

  1. 建立存儲多對多模型的外鍵對應(yīng)關(guān)系的關(guān)聯(lián)表
association_table = db.Table('association', db.Column('customer_id', db.Integer, db.ForeignKey('customer.id')),
                             db.Column('product_id', db.Integer, db.ForeignKey('product.id')))
  1. 建立兩個(gè)模型,secondary設(shè)為關(guān)聯(lián)表的名稱,具體可查看relationship
class Customer(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(10))
    work = db.Column(db.String(20))
    products = db.relationship('Product', secondary=association_table, back_populates='customers')

    def __repr__(self):
        return '姓名:{name} 公司:{work}'.format(name=self.name, work=self.work)


class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(10))
    price = db.Column(db.Float)
    customers = db.relationship('Customer', secondary=association_table, back_populates='products')

    def __repr__(self):
        return '產(chǎn)品類型:{name} 單價(jià):{price}'.format(name=self.name, price=self.price)
  1. 建立關(guān)系
@app.cli.command()
def insertcp():
    customer1 = Customer(name='程老板', work='大興有限公司')
    customer2 = Customer(name='李老板', work='弘成科技')
    customer3 = Customer(name='司馬老板', work='小馬加油有限公司')
    product1 = Product(name='絲綢', price=35.12)
    product2 = Product(name='鋁合金', price=54.45)
    product3 = Product(name='鹽', price=3.00)
    db.session.add(customer1)
    customer1.products.append(product1)
    customer1.products.append(product2)
    customer2.products.append(product2)
    customer3.products.append(product1)
    customer3.products.append(product3)
    product1.customers.append(customer1)
    product1.customers.append(customer3)
    product2.customers.append(customer2)
    product2.customers.append(customer1)
    product3.customers.append(customer3)
    db.session.commit()
    click.echo('insert')
  1. 查詢
@app.cli.command()
def querycp():
    customer = Customer.query.first()
    click.echo('{customer}  購買了  {products}'.format(customer=customer, products=customer.products))

查詢結(jié)果:

姓名:程老板 公司:大興有限公司  購買了  [產(chǎn)品類型:鋁合金 單價(jià):54.45, 產(chǎn)品類型:絲綢 單價(jià):35.12]

參考

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容