开发者

Access models in other project in a Django view cause "table doesn't exist" error

Base project structure

baseproject
    baseapp
        models.py
            class BaseModel(models.Model)
            ...

Other project structure:

project
    app
        views.py
        urls.py

project.app.views.py

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from django.conf import settings
from baseproject.baseapp.models import BaseModel
print BaseModel.objects.count()

it raised "Table 'project.baseapp_baemodel' doesn't exist" error when run from command line: "python views.py".

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'baseproject.settings'
from django.conf import settings
from baseproject.baseapp.models import BaseModel
print BaseModel.objects.count()

After changed project.settings to baseproject.settings, it works in command line.

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'baseproject.settings'
from django.conf import settings
from baseproject.bas开发者_如何学Pythoneapp.models import BaseModel

def someview(request):
    count = BaseModel.objects.count()
    return render_to_response(...)

But it still raised "Table 'project.baseapp_baemodel' doesn't exist" error when access the view by opening corresponding url in browser.

What's wrong in above code?


You are fighting against the framework here, and you'll be better off if you rethink your architecture. Django is built around the assumption that a project = a given set of INSTALLED_APPS, and the project settings name a database to which those apps are synced. It's not clear here what problem you have with just doing things that way, but whatever you're trying to achieve, it can be achieved without trying to import models from an app that is not in your current project's INSTALLED_APPS. That is never going to work reliably.

If there's an app you want in both projects, you should put it on your PYTHONPATH (or in virtualenvs) so both projects can access it, and put it in the INSTALLED_APPS of both projects. If you also need its data shared between the projects, you might be able to point both projects at the same database (though you'd need to be careful of other conflicting app names that you might not want to share data). Or you could use the multi-database support that's now in Django trunk to have the one project use the other project's database only for that one app.

My guess is if you back up a step and explain what you're trying to do, there are even better solutions available than those.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜