views:

79

answers:

1

In a Django view function which uses manual transaction committing, I have:

context = RequestContext(request, data)
transaction.commit()
return render_to_response('basic.html', data, context)  # Returns a Django ``HttpResponse`` object which is similar to a dictionary.

I think it is a better idea to do this:

context = RequestContext(request, data)
response = render_to_response('basic.html', data, context)
transaction.commit()
return response

If the page isn't rendered correctly in the second version, the transaction is rolled back. This seems like the logical way of doing it albeit there won't likely be many exceptions at that point in the function when the application is in production.

But... I fear that this might cost more and this will be replete through a number of functions since the application is heavy with custom transaction handling, so now is the time to figure out.

If the HttpResponse instance is in memory already (at the point of render_to_response()), then what does another reference cost? When the function ends, doesn't the reference (response variable) go away so that when Django is done converting the HttpResponse into a string for output Python can immediately garbage collect it?

Is there any reason I would want to use the first version (other than "It's 1 less line of code.")?

+2  A: 

You say, "there won't likely be many exceptions at that point in the function". This may not be true. Keep in mind that querysets are lazily fetched from the db, so in fact, a lot of your db activity could be inside the render_to_response call.

I'd use the second style. It's more correct in the sense that if something goes wrong in render_to_response, you want the transaction rolled back.

References cost almost nothing. Don't try to optimize them. Correctness is more important than absolute minimum memory footprint.

Ned Batchelder
@Ned Ah, good point. I forgot that Django `QuerySets` aren't used until the values are read (or if they're manipulated in ways that `QuerySet` doesn't support). What about memory usage (not that it's even a question of whether I should use the second version after your answer)?
orokusaki