Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

328
Visualizações
SQLAlchemy transaction not persisted

I recently had to implement a transaction on my app which goes as follows:

I have a:

  • "items" table
  • "tags" table which has "items.id" as ForeignKey
  • "descriptions" table which has "items.id" as ForeignKey

I now want to perform this transaction or rollback if it fails:

  • insert item into "items"
  • flush and get item.id (primary key)
  • insert tag into "tags" (using the item.id), this is a list of tags
  • insert description into "descriptions" (using the item.id), this is a list of descriptions

My database is sqlite.

my code:

db_item = models.Items(title=item.title, description=item.description,
                        quantity=item.quantity, images=item.images,
                        category_name=item.category_name, status=item.status,
                        organization_id=item.organization_id, price=item.price)


db.begin(subtransactions=True)
db.add(db_item)
db.flush()

db_tags_to_items = [models.ItemsAndTags(tag_name=tag, item_id=db_item.id) for tag in item.tags]
db_short_descriptions = [models.ItemsShortDescription(line=line, item_id=db_item.id) for line in item.descriptions]

db.add_all(db_tags_to_items)
db.add_all(db_short_descriptions)
db.commit()

If i return db_item it returns it with the id, however if i check the db that item was not persisted nor the tags or descriptions. What am i doing wrong as i get no error.

If more of my code is needed pleaste let me know, i use the FastAPI framework with SQLAlchemy.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I managed to get it working myself. Turns out db.begin(subtransactions=True) was not really needed.

this is my crud func now and it does what i need:

# create item as transaction
def create_item_v2(db: Session, item: items_schemas.ItemCreateV2):
    db_item = models.Items(title=item.title, description=item.description,
                        quantity=item.quantity, images=item.images,
                        category_name=item.category_name, status=item.status,
                        organization_id=item.organization_id, price=item.price)

    try:
        db.add(db_item)
        db.flush()
        db_tags_to_items = [models.ItemsAndTags(tag_name=tag, item_id=db_item.id) for tag in item.tags]
        db_short_descriptions = [models.ItemsShortDescription(line=line, item_id=db_item.id) for line in item.descriptions]

        db.add_all(db_tags_to_items)
        db.add_all(db_short_descriptions)
        db.commit()
        db.refresh(db_item)
        return db_item
    except:
        db.rollback()
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda