Last active
June 29, 2016 16:04
-
-
Save kageurufu/639af6df008b3d61cda7f21c10df946d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from . import app, db | |
class Drink(db.Model): | |
__tablename__ = 'drink' | |
id = db.Column(db.Integer, primary_key=True) | |
name = db.Column(db.String(64), index=True, unique=True) | |
recipe = db.relationship("DrinkIngredient", backref="drink") | |
def __init__(self, name): | |
self.name = name | |
def __repr__(self): | |
return '<Drink %r>' % (self.name) | |
class DrinkIngredient(db.Model): | |
__tablename__ = 'drink_ingredient' | |
drink_id = db.Column(db.Integer, db.ForeignKey("drink.id"), primary_key=True) | |
ingredient_id = db.Column(db.Integer, db.ForeignKey("ingredient.id"), primary_key=True) | |
units = db.Column(db.Numeric(4, 2)) # Total of 4 digits, 2 after decimal: 00.00 | |
ingredient = db.relationship("Ingredient") | |
def __init__(self, ingredient=None, units=None): | |
self.ingredient = ingredient | |
self.units = units | |
def __repr__(self): | |
return '<DrinkIngredient %g units of %r>' % (self.units, self.ingredient) | |
class Ingredient(db.Model): | |
__tablename__ = 'ingredient' | |
id = db.Column(db.Integer, primary_key=True) | |
name = db.Column(db.String(140)) | |
# subquery is also a valid option, if you want them loaded at query time. Select is the standard lazy loading | |
# This needs to be viewonly, so new DrinkIngredients are spuriously created without units | |
drinks = db.relationship("Drink", secondary=DrinkIngredient.__table__, lazy="select", viewonly=True) | |
def __init__(self, name): | |
self.name = name | |
def __repr__(self): | |
return '<Ingredient %r>' % (self.name) | |
@classmethod | |
def get_or_create(cls, name): | |
instance = cls.query.filter_by(name=name).first() | |
if not instance: | |
instance = cls(name) | |
db.session.add(instance) | |
db.session.flush([instance]) | |
return instance |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from models import Drink, DrinkIngredient, Ingredient | |
drink = Drink("Tequila Sunrise") | |
drink.recipe = [DrinkIngredient(Ingredient.get_or_create("Tequila"), 1), | |
DrinkIngredient(Ingredient.get_or_create("Grenadine"), 0.2), | |
DrinkIngredient(Ingredient.get_or_create("Orange Juice"), 4)] | |
db.session.add(drink) | |
db.session.commit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment