スクリプトを実行してデータベースにデータを追加したいと考えています。Django データベース API を介してアクセスしたいと思います。
唯一の問題は、これにアクセスするために何をインポートする必要があるのかわからないことです。
これはどのように達成できますか?
設定モジュールもインポートします
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"
from mysite.polls.models import Poll, Choice
トリックを行う必要があります。
これは、データ読み込みスクリプトの上部にあるものです。
import string
import sys
try:
import settings # Assumed to be in the same directory.
#settings.DISABLE_TRANSACTION_MANAGEMENT = True
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
#Setup the django environment with the settings module.
import django
import django.core.management
django.core.management.setup_environ(settings)
from django.db import transaction
これは、スクリプトで他の多くのことを行う前にすべて実行する必要があります。
もう 1 つの方法は、fixtures と manage.py を使用することです。ただし、データベースを初期化するために大量のデータ ロードを実行しようとしているだけであれば、これで問題なく動作するはずです。
また、何をしているかによって、すべてを 1 つのトランザクションで実行したい場合とそうでない場合があります。上記のトランザクション行のコメントを外し、コードを次のように構成します。
transaction.enter_transaction_management()
try:
#Do some stuff
transaction.commit()
finally:
transaction.rollback()
pass
transaction.leave_transaction_management()
shell
プロジェクト ディレクトリのスクリプトに引数を使用する場合はmanage.py
、設定を手動でインポートする必要はありません。
$ cd mysite/
$ ./manage.py shell
Python 2.5.2 (r252:60911, Jun 10 2008, 10:35:34)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from myapp.models import *
>>>
非対話的な使用の場合、カスタム コマンドを実装して で実行できますmanage.py
。
最もクリーンな解決策は、django 拡張機能を追加することです。
(virt1)tsmets@calvin:~/Documents/prive/rugby-club/proposal/kitu$ yolk -l Django - 1.3.1 - アクティブ ピグメント - 1.4 - アクティブ Python - 2.6.5 - 開発中 (/usr/lib/python2.6/lib-dynload) django-extensions - 0.7.1 - アクティブ ピップ - 1.0.2 - アクティブ setuptools - 0.6c11 - アクティブ wsgiref - 0.1.2 - 開発中 (/usr/lib/python2.6) 卵黄 - 0.4.1 - アクティブ
可能なコマンドのリストは、特に runscript コマンドで拡張されます。
独自のモデル ファイルに加えて、設定モジュールもインポートする必要があります。