On Aug 12, 2:24 am, Andy <selforgani...@gmail.com> wrote:
> When I create an object in Django, how long does it live?
>
> When Django finishes responding to a HTTP request, the Python process
> lives on to serve the next request. Does that mean all those objects
> that were created would continue to hang around?

It depends where they were created, and whether any references exist
outside that scope. Anything created within a view function, for
example, that never gets referenced at a higher scope, will go out of
scope when the view returns, and will therefore be deleted. If however
you put a reference to that object in the module-level scope, then the
object will persist. This can sometimes be an easy way to cache
objects that you will need on every request:

    my_cache = {}

    def my_view(request, object_id):
        obj = MyModel.objects.get(pk=object_id)
        my_cache[object_id] = obj
        return render_to_response('template.html', {'obj':obj})

In this case obj will persist across requests, because it is
referenced within my_cache. If you didn't do that assignment, it would
automatically be deleted when its only reference, the local 'obj'
variable, goes out of scope.

This is of course standard Python scoping rules - nothing particular
to Django here.
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to