Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to lazily evaluate ORM call after fixtures are loaded into db in Django?
    text
    copied!<p>I've got a module <code>pagetypes.py</code> that extracts a couple of constants (I shouldn't really use word constant here) from the db for later reuse:</p> <pre><code>def _get_page_type_(type): return PageType.objects.get(type=type) PAGE_TYPE_MAIN = _get_page_type_('Main') PAGE_TYPE_OTHER = _get_page_type_('Other') </code></pre> <p>then somewhere in views I do:</p> <pre><code>import pagetypes ... print pagetypes.PAGE_TYPE_MAIN #simplified </code></pre> <p>It all works fine when db has those records and I make sure it does... unless this code is under test. In that case I want to load those records into db via fixtures. The problem with that is that fixtures are not loaded (even <code>syncdb</code> is not run) by the time pagetypes module is imported resulting in <code>_get_page_type_</code> call failing with:</p> <pre><code>psycopg2.ProgrammingError: relation "pagetype" does not exist </code></pre> <p>Test runner always tries to import <code>pagetypes</code> module, because it is imported by view that is under test. </p> <p>How do I get around this problem?</p> <p>I was thinking of lazily loading pagetype constants <code>PAGE_TYPE_MAIN</code>, <code>PAGE_TYPE_OTHER</code>, but then I want it to fail early if those records are not in the db (or fixtures if under test), so I don't really know how to implement this.</p> <p>I was also thinking of object level caching and just call <code>PageType.objects.get(type=type)</code> whenever constant is used/called, but wouldn't that be an overkill? Calling orm without cache would result in too many db calls, which I want to prevent.</p> <p>It must be something very simple, but I can't work it out. ;-)</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