Search code examples
djangodjango-commands

Do I need close db connection in command [django]


According to this (http://djangosnippets.org/snippets/926/) snippet, connection closed in handle. But it is kind of old code.

In django 1.4, Do we must close connection? I looked through django code but I cann't find code that closes connection.

If django closes connection where is it?

Thank you.


Solution

  • As the snippet stated:

    # Close the DB connection. This is required as a workaround for an
    # edge case in MySQL: if the same connection is used to
    # create tables, load data, and query, the query can return
    # incorrect results. 
    

    From Django:

    So, yes, if you do something to deliberately create lots of connections, 
    lot of connections will be created. However, Django closes its connection to the 
    database at the end of each request/response cycle, so there is only one connection 
    in operation per thread or process handling requests and responses. If you're not 
    using the HTTP layer, it's still only one connection per thread of execution and 
    you are in complete control of the number of threads you create.
    

    https://code.djangoproject.com/ticket/9878