Delete the row as soon as a column reaches a specific value
<p>If this be my model:</p>

<pre><code>class Entity(Base):
    id = Column(Integer, primary_key=True)
    count = Column(Integer, default=0)
</code></pre>

<p>I want to delete any rows that reach <code>count</code> value of 3 (or any number).
How can I do that?
should I implement such deletion in the Controller of my web application and every time <code>count</code> is incremented, I check if it's value is 3 or not? How should I care about the concurrent requests that are changing the value? What is the best solution? </p>

<blockquote>
  <p>Should I implement the deletion in the controller of my web application?</p>
</blockquote>

<p>Yes. You should implement it in your controller. Just make sure you have a view that will be able to access your <code>delete</code> function in the controller.</p>

<blockquote>
  <p>Who [how] can I do that?</p>
</blockquote>

<p>Simple. In your controller, create a function that will handle the deletion. The delete function body should look like this:</p>

<pre><code>limit = 3 # The value of this variable is arbitrary.
Entity.query.filter(Entity.count == limit).delete()
# The two statements above can be simplified to
# Entity.query.filter(Entity.count == 3).delete()

db.session.commit()
</code></pre>

<p>Better yet, add a function parameter that will accept a value that will be the maximum value of a column in a row. It could look like this:</p>

<pre><code>def delete_entity(limit=3): # I set `limit` to 3 since that is what you have stated earlier in the question
    Entity.query.filter(Entity.count == limit).delete()
    db.session.commit()
</code></pre>

<blockquote>
  <p>Every time count is incremented, I check if the value is 3 or not? What is the best solution?</p>
</blockquote>

<p>It depends on what you want your application to do.</p>

python postgresql concurrency sqlalchemy locking