SQLAlchemy 多对多 - 中间表插入

问题描述 投票:0回答:0

我在通过 SQLAlchemy 中的关系添加项目时遇到问题。

我的模型

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

class Order(db.Model):

__tablename__ = 'orders' 

id = db.Column(
    db.Integer,
    primary_key=True,
    autoincrement = True
)

user_id = db.Column(
    db.Integer,
    db.ForeignKey('users.id'),
    nullable = False
)

timestamp = db.Column(        
    db.DateTime,
    nullable=False,
    default=datetime.utcnow()
)

total = db.Column(
    db.Float,
    nullable = False
)

products = db.relationship('Product', secondary = 'orders_products', backref = 'orders')

product_quantity = db.relationship('OrderProduct', backref = 'orders')

class OrderProduct(db.Model):
'''Mapping Order to Product'''

__tablename__ = 'orders_products'

id = db.Column(
    db.Integer, 
    primary_key = True,
    autoincrement = True
)

order_id = db.Column(
    db.Integer, 
    db.ForeignKey('orders.id'),
    primary_key = True
)

product_id = db.Column(
    db.Integer, 
    db.ForeignKey('products.id'),
    primary_key = True
)

quantity = db.Column(
    db.Integer,
    nullable = False
)`

执行:

cart = session[CART]
user = g.user
products = []

for c in cart:
    products.append(
        [Product.query.get_or_404(c.get('product_id')), c.get('quantity')]
    )

order = Order()

        for p in products:
            total += p[0].price
            order.products.append(p[0])
            order.product_quantity.append(OrderProduct(quantity= p[1]))

        order.user_id = user.id

        db.session.add(order)
        db.session.commit()

一旦值通过并且方法运行,我得到的结果是每个订单在 orders_products 表中有两个独立的实例。 订单表:

select * from orders;
id | user_id |         timestamp         | total
----+---------+---------------------------+-------
 1 |       1 | 2023-03-19 21:36:20.03719 |  3.25

在 orders_products 表中我有:

select * from orders_products;
order_product_id | order_id | product_id | quantity
------------------+----------+------------+----------
               1 |        1 |          1 |
               2 |        1 |            |        3

为了在 orders_products 表中有一个实例,我应该使用什么?

谢谢。

python postgresql flask-sqlalchemy
© www.soinside.com 2019 - 2024. All rights reserved.