1

I have a Django app which has this structure:

app/
    tests/
        __init__.py
        tests.py
    __init__.py
    test_model.py

In tests.py I import the test model like: from app.test_model import *. This works as expected: during testing, models are loaded, their corresponding database tables are created and so on.

But, if I move the test_model.py file in the tests/ directory:

app/
    tests/
        __init__.py
        test_model.py
        tests.py
    __init__.py

And do the import accordingly: from app.tests.test_model import *, it suddenly fails. Models are not detected, hence their database tables are not created and tests start to fail (DatabaseError: no such table: app_model).

Why is this happening? How should I avoid this and still place the test_model.py file in tests/?

linkyndy
  • 17,038
  • 20
  • 114
  • 194

3 Answers3

1

I assume that test_models.py is actually where you create all your models. Django looks for the model app name as the parent folder, and nesting it as you have may cause it to get stuck finding the app name. I don't fully understand the mechanics here, but I have experienced it before. The simple solution is to manually specify the app using the Meta option:

class MyModel(Model):

    ...

    class Meta:
        app_label = 'app'
aquavitae
  • 17,414
  • 11
  • 63
  • 106
0
from test_model import *

try this, it may help

-1

You should use a local import within a package:

from .test_model import *
arocks
  • 2,862
  • 1
  • 12
  • 20
  • It's the same result, models defined in `test_model.py` are not loaded, neither their tables. – linkyndy Jan 17 '14 at 13:42
  • Then you might have overlooked creating the models dynamically as mentioned in this [SO answer](http://stackoverflow.com/a/2672444/3107299) – arocks Jan 17 '14 at 13:47
  • @aquavitae's answer was cleaner and more 'Djangoish'. Thank you for helping :) – linkyndy Jan 17 '14 at 14:01
  • This is not correct, see [http://stackoverflow.com/questions/5160688/organizing-django-unit-tests/20932450#20932450](http://stackoverflow.com/questions/5160688/organizing-django-unit-tests/20932450#20932450) – SleepyCal May 02 '14 at 18:07