The Troublesome Active Record Pattern
The problem with this code<p><pre><code>  book = Book.get(isbn="978-0099466031")
  book.copies_in_stock -= 1
  book.save()  # WRONG! irreparable data loss here
</code></pre>
is that in SQL you should write it like this:<p><pre><code>  update books set 
    copies_in_stock = copies_in_stock - 1
  where isbn = '978-0099466031';
</code></pre>
No needs of transactions.<p>I don't remember how to do it with Django's ORM but in Rail's ActiveRecord I'd use directly the connection object<p><pre><code>  update_query = sanitize_sql(['update books set copies_in_stock = copies_in_stock - 1 where isbn = ?', isbn])
  ActiveRecord::Base.connection.execute(update_query)
</code></pre>
This saves a lot of programming pain, possibly skip some unnecessary bugs and get better performances.<p>sanitize_sql is from <a href="https://api.rubyonrails.org/classes/ActiveRecord/Sanitization/ClassMethods.html" rel="nofollow">https://api.rubyonrails.org/classes/ActiveRecord/Sanitizatio...</a>