Amin Etesamian Amin Etesamian - 2 months ago 16
Python Question

getting transaction result from transaction module

I am using Sqlalchemy and PostgreSQL. In my models I have a

Product
and an
Image
. I want each product to have multiple images. This is the product submission method:

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


in the last part that Im adding images to db. I need the
product_id
to set for the image. but I dont find a way to get it. Is there a way to get results from the transaction so I can find out what id the new product is assigned to?
DBSession.add()
and
transaction.commit()
both return
None
.

Answer

After using:

transaction.commit()

you can use product.id, because changes have been commited. So product has now its id:

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