Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Code that tries to access the models before they're created can pretty much exist only at the module level; it would have to be executable code run when the module is imported, as your example indicates. This is, as you've guessed, the reason by syncdb fails. It tries to import the module, but the act of importing the module causes application-level code to execute; a "side-effect" if you will.</p> <p>The desire to avoid module imports that cause side-effects is so strong in Python that the <code>if __name__ == '__main__':</code> convention for executable python scripts has become commonplace. When just loading a code library causes an application to start executing, headaches ensue :-)</p> <p>For Django apps, this becomes more than a headache. Consider the effect of having <code>oldJob.delete()</code> executed every time the module is imported. It may seem like it's executing only once when you run with the Django development server, but in a production environment it will get executed quite often. If you use Apache, for example, Apache will frequently fire up several child processes waiting around to handle requests. As a long-running server progresses, your Django app will get bootstrapped every time a handler is forked for your web server, meaning that the module will be imported and <code>delete()</code> will be called several times, often unpredictably. A signal won't help, unfortunately, as the signal could be fired every time an Apache process is initialized as well.</p> <p>It isn't, btw, just a webserver that could cause your code to execute inadvertently. If you use tools like epydoc, for example they will import your code to generate API documentation. This in turn would cause your application logic to start executing, which is obviously an undesired side-effect of just running a documentation parser. </p> <p>For this reason, cleanup code like this is either best handled by a cron job, which looks for stale jobs on a periodic basis and cleans up the DB. This custom script can also be run manually, or by any process (for example during a deployment, or as part of your unit test <code>setUp()</code> function to ensure a clean test run). No matter how you do it, the important point is that code like this should always be executed <em>explicitly</em>, rather than <em>implicitly</em> as a result of opening the source file.</p> <p>I hope that helps. I know it doesn't provide a way to determine if syncdb is running, but the syncdb issue will magically vanish if you design your Django app with production deployment in mind.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload