Instantly share code, notes, and snippets.

What would you like to do?
sqlalchemy-cheatsheet from tutorial
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
class Author(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
books = db.relationship('Book', backref='author')
def __repr__(self):
return '<Author:{}>'.format(
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Text)
content = db.Column(db.Text)
author_id = db.Column(db.Integer, db.ForeignKey(''))
def __repr__(self):
return '<Book:{}>'.format(self.title)
categories = db.Table('categories',
db.Column('category_id', db.Integer, db.ForeignKey('')),
db.Column('book_id', db.Integer, db.ForeignKey(''))
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
books = db.relationship('Book', secondary=categories,
backref=db.backref('categories', lazy='dynamic'))
def __repr__(self):
return '<Category:{}>'.format(
with app.app_context():
bob = Author(name='Bob')
dune = Book(title='Dune')
moby_dick = Book(title='Moby Dick')
carol = Author(name='Carol')
ring_world = Book(title='Ring World')
fahrenheit = Book(title='Fahrenheit 451')
bob.books = [dune, moby_dick]
carol.books = [ring_world, fahrenheit]
author = Author.query.filter_by(name='Bob').first()
print author # <Author:Carol>
print author.books # [<Book:Ring World>, <Book:Fahrenheit 451>]
dune_book = Book.query.filter_by(title='Dune').first()
print dune_book # <Book:Dune>
print # <Author:Bob>
scifi = Category(name='Science Fiction')
classic = Category(name='Classic')
classic.books = [moby_dick, dune, fahrenheit]
scifi.books = [dune, ring_world]
db.session.add_all([classic, scifi])
print dune, dune.categories.all()
print dune.categories.filter('sci%')).all()
alice = Author(name='Alice')
beowulf = Book(title='Beowulf') = alice
beowulf.categories = [classic]
print Author.query.join(Author.books).filter(
print Category.query.join(Category.books).filter(

This comment has been minimized.

allprogrammers commented Jul 8, 2017

Book object doesn't have attribute author
it has author_id how does it get author?

Edit: Okay i got it. it is in backref

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment