从交易模块获取交易结果

从交易模块获取交易结果

问题描述:

我正在使用Sqlalchemy和PostgreSQL。在我的模型中,我有一个Product和一个Image。我希望每个产品都有多个图像。这是产品提交方法:从交易模块获取交易结果

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() 

在我将图像添加到数据库的最后部分。我需要product_id来设置图像。但我没有找到办法。有没有办法从交易中获得结果,以便我可以找出新产品分配的ID? DBSession.add()transaction.commit()都返回None

使用后:

transaction.commit() 

可以使用product.id,因为更改已COMMITED。所以产品现在它的ID:

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

为什么我没有为上帝的缘故尝试这个? :D tnx :) – Juggernaut

+0

也许只是因为在使用其他ORM时通过提交获取了此值。没问题。 ;) – turkus

+0

@AminEtesamian你为什么拒绝批准? – turkus

,关键是要DBSession.flush()添加图像,从而使加入将完成并product.id将可以访问后。