class StoreModel(db.Model): __tablename__ = 'stores' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) items = db.relationship('ItemModel', lazy='dynamic') def __init__(self, name): self.name = name def json(self): return { 'name': self.name, 'items': [item.json() for item in self.items.all()] } @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class ItemModel(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) # new for this section - new storeID column store_id = db.Column(db.Integer, db.ForeignKey('stores.id')) # SQL Alchemy creates the store and id in StoreModel table for this relationship store = db.relationship('StoreModel') def __init__(self, name, price, store_id): self.name = name self.price = price self.store_id = store_id def json(self): return {'name': self.name, 'price': self.price} @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class ItemModel(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) def __init__(self, name, price): self.name = name self.price = price def json(self): return {'name': self.name, 'price': self.price} @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class UserModel(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80)) password = db.Column(db.String()) def __init__(self, username, password): self.username = username self.password = password def save_to_db(self): db.session.add(self) db.session.commit() @classmethod def find_by_username(cls, username): return cls.query.filter_by(username=username).first() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first()