SqlAlchemy Flask - 具有两列以上的关联表

时间:2016-03-05 02:20:02

标签: python flask flask-sqlalchemy

我正在创建一个购物车,为此我在Flask中使用以下模型:

line_item = db.Table('line_item',
                     db.Column('cart_id', db.Integer, db.ForeignKey('cart.id')),
                     db.Column('product_id', db.Integer, db.ForeignKey('product.id')),
                     db.Column('price', db.Float)
                     )


class Cart(db.Model):
    id = db.Column(db.Integer, primary_key=True)


class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Unicode(64), index=True, unique=True)
    description = db.Column(db.Unicode(500), index=True, unique=True)
    image_url = db.Column(db.Unicode(128))
    price = db.Column(db.Float)
    line_item = db.relationship('Cart', secondary=line_item, backref=db.backref('products', lazy='dynamic'))

我想在关联表“line_item”中使用额外的列来包含价格,以便在用户将产品添加到购物车时保存产品的价格。

我知道如果没有price列,我会执行以下操作来添加此数据。

p = Product()
c = Cart()
p.line_item.append(c)
db.session.add(p)
db.session.commit()

我应该如何在关联表中插入price

1 个答案:

答案 0 :(得分:0)

db.Model未经测试的代码使用LineItem,如下所示:

class LineItem(db.Model):
    __tablename__ = 'line_items'        
    cart_id = db.Column(db.Integer, db.ForeignKey('carts.id'), primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('products.id'), primary_key=True)
    price = db.Column(db.Float)    
    cart = db.relationship("Cart", back_populates="line_items")
    product = db.relationship("Product", back_populates="carts")


class Cart(db.Model):
    __tablename__ = 'carts'
    id = db.Column(db.Integer, primary_key=True)
    line_items = db.relationship(LineItem, back_populates="cart")    


class Product(db.Model):
    __tablename__ = 'products'  
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Unicode(64), index=True, unique=True)
    description = db.Column(db.Unicode(500), index=True, unique=True)
    image_url = db.Column(db.Unicode(128))
    price = db.Column(db.Float)
    carts = db.relationship(LineItem, back_populates="product")    


p = Product()
c = Cart()

line_item = LineItem()
line_item.price = p.price
line_item.product = p

c.line_items.append(line_item)