Note that there are some explanatory texts on larger screens.

plurals
  1. POSQLAlchemy: Re-saving model's unique field after trying to save non-unique value
    text
    copied!<p>In my SQLAlchemy app I have the following model:</p> <pre><code>from sqlalchemy import Column, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) class MyModel(declarative_base()): # ... label = Column(String(20), unique=True) def save(self, force=False): DBSession.add(self) if force: DBSession.flush() </code></pre> <p>Later in code for every new <code>MyModel</code> objects I want to generate <code>label</code> randomly, and just regenerate it if the generated value is already exist in DB.<br> I'm trying to do the following:</p> <pre><code># my_model is an object of MyModel while True: my_model.label = generate_label() try: my_model.save(force=True) except IntegrityError: # label is not unique - will do one more iteration # (*) pass else: # my_model saved successfully - exit the loop break </code></pre> <p>but get this error in case when first generated <code>label</code> is not unique and <code>save()</code> called on the second (or later) iteration:</p> <pre><code> InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (IntegrityError) column url_label is not unique... </code></pre> <p>When I add <code>DBSession.rollback()</code> in the position (*) I get this:</p> <pre><code> ResourceClosedError: The transaction is closed </code></pre> <p>What should I do to handle this situation correctly?<br> Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload