G
G
greenpower2015-04-11 16:41:34
PostgreSQL
greenpower, 2015-04-11 16:41:34

How to implement many-to-many relationships with an additional field in SqlAlchemy?

I have recipes that have a list of ingredients.
Each ingredient belongs to a category of ingredients.

from app import db

followers = db.Table('followers',
    db.Column('follower_id', db.Integer, db.ForeignKey('recipes.id')),
    db.Column('followed_id', db.Integer, db.ForeignKey('product.id'))
)

class Category(db.Model):
    __tablename__ = 'category'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), nullable=False)


    def __init__(self, name):
        self.name = name


    def __repr__(self):
        return "Category name %s" % (self.name)


 

class Product(db.Model):
    __tablename__ = 'product'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), nullable=False)
    filename = db.Column(db.String(250), nullable=True)
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship(Category)


    def __init__(self, name, filename, category):
        self.name = name
        self.filename = filename
        self.category = category


    def __repr__(self):
        return "Product %s, img %s" % (self.name, self.filename)



class Recipe(db.Model):
    __tablename__ = 'recipes'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), nullable=False)
    image = db.Column(db.String(250), nullable=True)
    followed = db.relationship('Product',
        secondary=followers,
        backref=db.backref('followers', lazy='dynamic'),
        lazy='dynamic')


    def follow(self, product):
        if not self.is_following(product):
            self.followed.append(product)
            return self


    def unfollow(self, product):
        if self.is_following(product):
            self.followed.remove(product)
            return self


    def is_following(self, product):
        return self.followed.filter(followers.c.followed_id == product.id).count()


    def followed_products(self):
        return Product.query.join(followers, (followers.c.followed_id == Product.id)).filter(followers.c.follower_id == self.id)


I want to store another string or number indicating the quantity of the ingredient.
Help me figure out how to screw it up.

Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zsts, 2015-04-13
@greenpower

Забудьте на время про связь продукта с категорией. У вас это сделано, и это никак не влияет на связь продуктов с рецептами.
Сущность, связывающая рецепты с продуктами, будет состоять из следующих данных:
(условно, таблица Components)
Теперь, для каждого рецепта собираем набор компонентов в таком виде:
<id_рецепта> <id_компонента>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question