سؤال

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/?

هل كانت مفيدة؟

المحلول

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'

نصائح أخرى

from test_model import *

try this, it may help

You should use a local import within a package:

from .test_model import *
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top