Skip to content

Instantly share code, notes, and snippets.

@martinmckenna
Created January 14, 2019 01:46
Show Gist options
  • Save martinmckenna/eb5eeee5869663fc8f2e52a5e7ef72c9 to your computer and use it in GitHub Desktop.
Save martinmckenna/eb5eeee5869663fc8f2e52a5e7ef72c9 to your computer and use it in GitHub Desktop.
many to many cocktails ingredients
from flask import Flask
from settings import db, ma
from models.ing_in_cocktails import CocktailIngredient, CocktailIngredientSchema
from models.ingredients import Ingredient, IngredientSchema
class Cocktail(db.Model):
__tablename__ = 'cocktails'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
glass = db.Column(db.String(20), nullable=False)
finish = db.Column(db.String(20), nullable=True)
ingredients = db.relationship(
'CocktailIngredient',
# secondary='ings_in_cocktail',
backref=db.backref('cocktails'),
# primaryjoin=id == CocktailIngredient.cocktail_id
)
# Necessary for transforming sqlalchemy data into serialized JSON
class CocktailSchema(ma.ModelSchema):
# this is responsible for returning all the ingredient data on the cocktail
ingredients = ma.Nested(CocktailIngredientSchema, many=True, strict=True)
class Meta:
model = Cocktail
from flask import Flask
from settings import db, ma
class Ingredient(db.Model):
__tablename__ = 'ingredients'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
ing_type = db.Column(db.String(20), nullable=False)
class IngredientSchema(ma.ModelSchema):
class Meta:
model = Ingredient
from flask import Flask
from settings import db, ma
from models.ingredients import Ingredient, IngredientSchema
class CocktailIngredient(db.Model):
__tablename__ = 'ings_in_cocktail'
ing_id = db.Column(db.Integer, db.ForeignKey('ingredients.id'), primary_key=True)
cocktail_id = db.Column(db.Integer, db.ForeignKey('cocktails.id'), primary_key=True)
ounces = db.Column(db.Integer, nullable=False)
ingredient = db.relationship('Ingredient')
# Necessary for transforming sqlalchemy data into serialized JSON
class CocktailIngredientSchema(ma.ModelSchema):
ingredient = ma.Nested(IngredientSchema, strict=True)
class Meta:
model = CocktailIngredient
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment