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

南楼画角 提交于 2020-01-05 00:49:10

问题


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.baseapp.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?


回答1:


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.



来源:https://stackoverflow.com/questions/2069254/access-models-in-other-project-in-a-django-view-cause-table-doesnt-exist-erro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!