Skip to content

Instantly share code, notes, and snippets.

@tspng
Last active July 26, 2021 14:10
Show Gist options
  • Save tspng/f006b6985f4815843b236a71bd9a72fd to your computer and use it in GitHub Desktop.
Save tspng/f006b6985f4815843b236a71bd9a72fd to your computer and use it in GitHub Desktop.
SQLAlchemy Many-to-One relationship and cascade example
class Image(db.Model):
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.String(255))
class ThingWithImage(db.Model):
id = db.Column(db.Integer, primary_key=True)
image_id = db.Column(db.Integer, db.ForeignKey("image.id"))
image = db.relationship("Image", foreign_keys=[image_id])
class ThingWithMultipleImages(db.Model):
id = db.Column(db.Integer, primary_key=True)
image_id = db.Column(db.Integer, db.ForeignKey("image.id"))
logo_id = db.Column(db.Integer, db.ForeignKey("image.id"))
image = db.relationship("Image", foreign_keys=[image_id])
logo = db.relationship("Image", foreign_keys=[logo_id])
def delete(self, commit=True):
# TODO: Would be nice if unused Image objects could be removed as well
if self.image:
# This probably fails if some other object has a foreign key pointing to self.image's entry
db.session.delete(self.image)
if self.logo:
# Same problem as with self.image
db.session.delete(self.logo)
db.session.delete(self)
commit and db.session.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment