0% found this document useful (0 votes)
14 views2 pages

Sqla Cheatsheet

This document serves as a cheat sheet for SQLAlchemy, detailing how to create models, perform queries, and manage relationships in a database. It includes examples of making and deleting instances, filtering records, and handling many-to-many relationships. Key operations such as creating and dropping tables, committing transactions, and navigating relationships between models are also covered.

Uploaded by

j2prt2f2mt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views2 pages

Sqla Cheatsheet

This document serves as a cheat sheet for SQLAlchemy, detailing how to create models, perform queries, and manage relationships in a database. It includes examples of making and deleting instances, filtering records, and handling many-to-many relationships. Key operations such as creating and dropping tables, committing transactions, and navigating relationships between models are also covered.

Uploaded by

j2prt2f2mt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

SQLAlchemy Cheat Sheet

Making Models Getting and Filtering


from flask_sqlalchemy import SQLAlchemy Getting record by primary key:
db = SQLAlchemy()
fluffy = Pet.query.get("fluffy") or Pet.query.get_or_404("fluffy")
class Pet(db.Model):
__tablename__ = "pets" Simple Filtering: (returns a “query”, not the answer—see fetching below)
id = db.Column(db.Integer,
primary_key=True, Pet.query.filter_by(species="cat")
autoincrement=True)
name = db.Column(db.String(50), Flexible filtering: (returns “query”)
nullable=False,
unique=True) Pet.query.filter(Pet.species == "dog")
species = db.Column(db.String(30), nullable=True) also: Pet.hunger != 10 , .filter(Pet.hunger < 10)
hunger = db.Column(db.Integer, nullable=False, default=20)
also: Pet.name.like('%uff%') , Pet.hunger.in_([2, 7])
SQLAlchemy types: OR: expr | expr , AND: expr & expr , NOT: ~ expr

Integer , String(len) , Text , Boolean , DateTime , Float , Numeric Grouping, Ordering, Offsetting, Limiting:

Field options (all default to False): .group_by('species')


.group_by('species').having(db.func.count() > 2)
primary_key , autoincrement , nullable , unique
.order_by('species') , .offset(10) , .limit(10)
Creating/Dropping Tables:
Getting lightweight tuples, not instances of model class:
db.create_all() , db.drop_all()
db.session.query(Pet.name, Pet.hunger) → [("fluffy", 10), ("bob", 3)]

Fetching:
Making and Deleting Instances
query.get(pk)
Making an instance: query.all() (get all as list)
query.first() (get first record or None)
fluffy = Pet(name="Fluffy", species="feline catus")
query.one() (get first record, error if 0 or if > 1)
Adding model instance to database session (only need to do 1st time adding)
query.one_or_none() (get first record, error if > 1, None if 0)
db.session.add(fluffy) or db.session.add_all([fluffy, bob]) query.count() (returns # of elements)

Committing or rolling back transactions:

db.session.commit() , db.session.rollback()

Deleting

db.session.delete(fluffy) or Pet.query.filter(...).delete()
Relationships Many to Many Relationships

depts emps assignments


emps projs
code [PK] id [PK] emp_id [PK,FK]
dept_code [FK] id [PK] proj_code [PK,FK] code [PK]
role
class Employee(db.Model):
__tablename__ = "emps" class Employee(db.Model):
id = db.Column(db.Integer, primary_key=True, auto_increment=True) __tablename__ = "emps"
dept_code = db.Column(db.Text, db.ForeignKey('depts.dept_code')) id = db.Column(db.Integer, primary_key=True, auto_increment=True)
# can nav from employee to projects, or project to employees
class Department(db.Model): projects = db.relationship(
__tablename__ = "depts" 'Project', secondary='assignments', backref='employees')
dept_code = db.Column(db.Text, primary_key=True)
employees = db.relationship('Employee', backref='department') class Project(db.Model):
__tablename__ = "emps_projs"
code = db.Column(db.Text, primary_key=True)
Can navigate like:
class Assignment(db.Model):
>>> jane.department # <Department finance> __tablename__ = "assignments"
>>> finance.employees # [<Employee 1>, <Employee 2>] emp_id = db.Column(
db.Integer, db.ForeignKey("emps.id"), primary_key=True)
proj_code = db.Column
(db.Text, db.ForeignKey("projs.code"), primary_key=True)
role = db.Column(db.Text)

# if you want to nav emp<->assignment and dept<->assignment


project = db.relationship("Project", backref="assignments")
project = db.relationship("Employee", backref="assignments")

Can navigate like:

>>> jane.projects # [<Project A>, <Project B>]


>>> proj_a.employees # [<Employee 1>, <Employee 2>]

>>> jane.assignments # [<Assignment jane A>, <Assignment jane B>]


>>> proj_a.assignments # [<Assignment jane A>, <Assignement bob A>]
>>> asn_jane_a.employee # <Employee 1>
>>> asn_jane_a.project # <Project A>

You might also like