Django Gets Transactions «

Code: , ,

Jacob Kaplan-Moss added transaction support to the magic-removal branch of Django just a few minutes ago. It’s one of the many changes to come out of the sprint. Usage will look something like this (based on Jacob’s docs and chatting with him in #django-sprint):

from django.db import transaction

def view(request):
# you make changes to your objects, calling on them as normal

# when you commit, all changes to all objects will be commited to your database

# an excellent idea would be to wrap in a try/except block
# do your stuff

I couldn’t find a good doc quick for Python decorators (that bit with the @ before the function declaration) for people who haven’t used them before, so if someone has a good one, please post it in the comments below.

Here’s a link to the full docs and for those interested in the nitty-gritty, here’s a link to the code checkin.

And before you ask, magic-removal is expected to be merged to trunk before the end of March.


  1. I don’t know if you have this set up this way, but on LJ the only thing that’s showing up is the post title. You can’t read the whole entry without clicking through to this site.

  2. Yeah, it’s deliberate. I’m trying to keep the discussion here, so I’m luring the LJ readers over. And most of them don’t care about the topics I’m raising, so I might as well not take up too much space on their friends lists.

  3. One thing to note…you use 2.4-style @ decorators in all your examples, but (thank goodness) it doesn’t appear that the checkin used them. It would be a rather large prereq change to change from requiring 2.3 to 2.4! You might want to throw in a 2.3-style example along with a note for those who already have running django implementations on 2.3.
    (eg, no @, view = transaction.commit_manually(view) at end, IIRC).

    Just a thought!

  4. Oops, I didn’t write the full docs I linked to, Jacob did. You’re right, the @-style is a 2.4ism, but I’d rather look at it as a good excuse to upgrade, heh. I still don’t have a good decorator article to link to, and having one would fill the gap you pointed out nicely.

    Thanks for the clarification.

  5. Nice article and it works as advertised, but wouldn’t you put the transaction code in your model rather than in your view?

    Also, if the transaction was complex and involved modification of multiple objects I can see the need for a business logic layer to be added, rather than the view talking directly to the model.

  6. Where I put the transaction would depend on what it actually did, but yes, they should probably be in the model. This was just the quickest, shortest example I could write at the time.

Leave a Reply

Your email address will not be published.