今朝からやってみてdjangoの複数のデータベースへのアクセスについては、こちらのすべての記事を読んでください。同じサーバー上の別のデータベースにアクセスしたいのですが、settings.pyにエイリアスを使用してデータベースを含めました。クエリセットでusing()を使用しようとすると、グローバル名「Objectname」が存在しないというエラーが表示されます。私はdjango 1.4でpostgresql 9.1を使用しています
これが機能するためにインポートする必要があるものはありますか?コンソール(python manage.py shell)またはビューのどちらでも動作しません。
settings.pyからのデータベースのセットアップは次のとおりです。
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2", # Add "postgresql_psycopg2", "postgresql", "mysql", "sqlite3" or "oracle".
"NAME": "testing", # Or path to database file if using sqlite3.
"USER": "xxxx", # Not used with sqlite3.
"PASSWORD": "xxxx", # Not used with sqlite3.
"HOST": "localhost", # Set to empty string for localhost. Not used with sqlite3.
"PORT": "xxxx", # Set to empty string for default. Not used with sqlite3.
},
"app_data": {
"ENGINE": "django.db.backends.postgresql_psycopg2", # Add "postgresql_psycopg2", "postgresql", "mysql", "sqlite3" or "oracle".
"NAME": "applications", # Or path to database file if using sqlite3.
"USER": "xxxx", # Not used with sqlite3.
"PASSWORD": "xxxx", # Not used with sqlite3.
"HOST": "localhost", # Set to empty string for localhost. Not used with sqlite3.
"PORT": "xxxx", # Set to empty string for default. Not used with sqlite3.
},
"ppp_data": {
"ENGINE": "django.db.backends.postgresql_psycopg2", # Add "postgresql_psycopg2", "postgresql", "mysql", "sqlite3" or "oracle".
"NAME": "platform", # Or path to database file if using sqlite3.
"USER": "xxxx", # Not used with sqlite3.
"PASSWORD": "xxxx", # Not used with sqlite3.
"HOST": "localhost", # Set to empty string for localhost. Not used with sqlite3.
"PORT": "xxxx", # Set to empty string for default. Not used with sqlite3.
}
}
コンソールからのコードは次のとおりです。
>>> MyModel.objects.using("app_data").all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name "MyModel" is not defined
ビューからのエラーは次のとおりです。
NameError at /myapp/view
global name "MyModel" is not defined
助けてください!
編集済み: ちょっとした背景を説明するために、異なるデータベースを使用して1つのサーバーで3つの異なるアプリを実行しており、表示するために異なるアプリのレコードにアクセスしたかったです。 3つのアプリはapp、ppp、testingであり、テストアプリからappおよびpppデータにアクセスしようとしています。
回答:
回答№1は0他のアプリのアプリパスをwsgiファイルに追加する必要がありました。
import os, sys
sys.path.append("/opt/www/test")
sys.path.append("/opt/www/app")
sys.path.append("/opt/www/ppp")
その後、他のアプリからモデルをインポートできます
from pp_app.myapp.models import MyModel
from pp_ppp.myapp.models import MyModel
次に、これにより、ビューでusing()メソッドを使用してレコードを取得できました。
data1 = MyModel.objects.using("app_data").all()
data2 = MyModel.objects.using("ppp_data").all()
これが他の人に役立つことを願っています