首先导入Flask和SQLAlchemy模块:
Flas
SQLAlchemy
from flask import Flask from flask_sqlalchemy import SQLAlchemy
声明app和db对象:
app
db
app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///inquestion.db' db = SQLAlchemy(app)
有三个表:Artist,Album和Genre。该Artist对象可以链接到多个Albums。并且该Album对象可以链接到多个对象Artists。的albums_to_artists_table是保持之间的关系Artists和Albums紧密的:
Artist,Album
Genre
Albums
Artists
albums_to_artists_table
albums_to_artists_table = db.Table('albums_to_artists_table', db.Column('album_id', db.Integer, db.ForeignKey('album.id')), db.Column('artist_id', db.Integer, db.ForeignKey('artist.id'))) class Genre(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) class Album(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) genre_id = db.Column(db.Integer, db.ForeignKey('genre.id')) artists = db.relationship('Artist', backref='albums', lazy='dynamic', secondary=albums_to_artists_table) class Artist(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) _albums = db.relationship('Album', secondary=albums_to_artists_table, backref=db.backref('albums_to_artists_table_backref', lazy='dynamic'))
所以我们有Artist链接到Album这是与Genre它看起来像这样:Artist> Album> Genre。
Artist> Album> Genre
完成此设置后,我们Genre首先创建对象:
db.drop_all() db.create_all() genre = Genre(name='Heavy Metal') db.session.add(genre) db.session.commit()
然后是两张专辑:
album1 = Album(name='Ride the Lightning', genre_id = genre.id) album2 = Album(name='Master of Puppets ', genre_id = genre.id) db.session.add(album1) db.session.add(album2) db.session.commit()
和艺术家:
artist = Artist(name='Metallica', _albums=[album1, album2]) db.session.add(artist) db.session.commit()
创建数据库后,我们可以查询Albums链接到的内容Genre:
print Album.query.filter_by(genre_id=1).all()
以及Artists链接到Album:
print Artist.query.filter(Artist._albums.any(id=album1.id)).all()
现在,我想查询Artists与Genre传递genre.id 链接的所有链接。如何实现呢?
Genre传
genre.id
你可以在中应用过滤器Artist.albums.any(),这将生成一个子查询:
Artist.albums.any()
Artist.query.filter(Artist.albums.any(genre_id=genre.id)).all()
或者你可以join()在专辑上使用:
join()
Artist.query.join(Artist.albums).filter_by(genre_id=genre.id).all()