从事务模块

时间:2016-10-02 21:45:56

标签: python sqlalchemy

我正在使用Sqlalchemy和PostgreSQL。在我的模型中,我有ProductImage。我希望每个产品都有多个图像。这是产品提交方法:

def submit_product(self, **kwargs):

    product = Product(
        title=kwargs['title'],
        sub_category_id=kwargs['sub_category_id'],
        year_of_production=kwargs['year_of_production'],
        country_of_production=kwargs['country_of_production'],
        quantity=kwargs['quantity'],
        price=kwargs['price'],
        account_id=session.get('account_id', None)
        )


    DBSession.add(product)
    transaction.commit()

    for image in kwargs['images']:
        image = Image(
            product_id= # what should I put here?,
            image=image.file.read()
        )
        DBSession.add(image)
    transaction.commit()

在最后一部分我将图像添加到db。我需要product_id来设置图片。但我找不到一种方法来获得它。有没有办法从交易中获得结果,以便我可以找出新产品分配给哪个ID? DBSession.add()transaction.commit()都返回None

2 个答案:

答案 0 :(得分:1)

使用后:

transaction.commit()

您可以使用product.id,因为已经提交了更改。所以产品现在已经是它的ID:

for image in kwargs['images']:
    image = Image(
        product_id=product.id, # what should I put here?,
        image=image.file.read()
    )
    DBSession.add(image)

答案 1 :(得分:1)

诀窍是在添加图片后DBSession.flush(),以便完成添加并可以访问product.id