I read that we can overwrite the save() for any model to do something
before/after its save. But my issue is, how can I be sure that what i
save + what the model needs to save happen as a transaction, so if
either fails, the whole thing fails.
Example. I want to keep a total inventory count in a model called
"Item". I want to then be able to add entries in model ItemEntry,
which has a count_used. When the ItemEntry model is being saved, I
want to deduct the amount from the total in corresponding "Item"
model. But if I do something like:
# forgive the syntax, I'm winging it right now
class ItemEntry(models.Model):
....
def save():
i = Item.objects.get(pk=5)
i.count = i.count - used_value
i.save()
self.save()
if either fails in the "save()", the data will be out of sync. Is
there a way to wrap this in a "transaction", without going into the
database itself and creating triggers, etc.?
Can I specify trigger like behaviour in the model definition? I would
like to not have changes in some other place(e.g. DB), since django's
advantage is centrally organizing things.
Thanks.
Django has a reasonably complete set of transaction control
functionality. The official documentation is at:
http://docs.djangoproject.com/en/dev/topics/db/transactions/
I also wrote a blog entry about it:
http://thebuild.com/blog/2009/11/07/django-postgresql-and-transaction-management/
(The blog entry is with regards to PostgreSQL, but it's pretty
generally applicable.)
None of it involved overriding .save(), I'm pleased to report.
--
-- Christophe Pettus
x...@thebuild.com
In your experience, would it be better to use the
"@transaction.commit_on_success" decorator for the functions that need
it, or turn on transaction middleware for the whole app?
Thanks
> --
>
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
>
>
>
> In your experience, would it be better to use the
> "@transaction.commit_on_success" decorator for the functions that need
> it, or turn on transaction middleware for the whole app?
My general approach, when using PostgreSQL as the backend, is to turn
on Autocommit, and then use either the commit_on_success decorator or
manual transaction calls for those functions that update the database.
The ideal situation is to have functions that just query the database
run outside of an explicit transaction, wrapping those update
operations that require it in their own transactions.
The downside of that is that using Autocommit affects the entire
project, so other applications that you didn't write may be surprised
when the default Django behavior of opening a transaction for each
view method is defeated.