2008-10-08 2 views
7

데이터베이스를 채우기 위해 스크립트를 실행하고 싶습니다. Django 데이터베이스 API를 통해 액세스하고 싶습니다.내 모델에 액세스하려면 무엇을 가져와야합니까?

유일하게 문제는 이것에 액세스하려면 무엇을 가져올 필요가 있는지 모른다는 것입니다.

어떻게 달성 할 수 있습니까?

답변

12

너무

import os 
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" 

from mysite.polls.models import Poll, Choice 

트릭을 할해야 설정 모듈을 가져옵니다. 프로젝트 디렉토리에 manage.py 스크립트에 shell 인수를 사용하는 경우

0

자신의 모델 파일 외에도 설정 모듈을 가져와야합니다.

5

, 수동으로 설정을 가져올 필요가 없습니다 :

비 대화식 사용을 위해
$ 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 * 
>>> 

당신은 custom command를 구현하고이를 실행할 수 있습니다 manage.py.

+0

뭔가를 놓치지 않는 한 manage.py에는 Django 1.0에 runscript 부속 명령이 없습니다.이 기능을 제공하기 위해 사용자 정의 응용 프로그램을 사용하는 경우 언급해야합니다. –

6

이것은 내 데이터로드 스크립트의 맨 위에 있습니다.

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 

이 내용은 스크립트에서 많이 수행하기 전에 모두 실행되어야합니다.

또 다른 방법은 고정 장치와 manage.py를 사용하는 것입니다. 비록 데이터베이스를 초기화하기 위해 벌크 데이터로드를 수행하려고한다면 이것은 정상적으로 작동합니다.

당신이하는 일에 따라 한 번에 모든 일을 처리 할 수도 있고 원치 않을 수도 있습니다. 위의 트랜잭션 행의 주석 처리를 제거하고 이와 비슷한 코드 구조를 만드십시오.

transaction.enter_transaction_management() 
try: 
    #Do some stuff 
    transaction.commit() 
finally: 
    transaction.rollback() 
    pass 
transaction.leave_transaction_management() 
+0

+1, 내 프로젝트의 루트에서 실행 중, 위의 허용 대답은 작동하지 않지만 귀하의 않습니다! – pufferfish

+1

"sys.exit (1)"줄을 들여 쓰기하지 않아야합니까? –

1

가장 안전한 해결책은 django 확장을 추가하는 것입니다.

 
(virt1)[email protected]:~/Documents/prive/rugby-club/proposal/kitu$ yolk -l 
Django   - 1.3.1  - active 
Pygments  - 1.4   - active 
Python   - 2.6.5  - active development (/usr/lib/python2.6/lib-dynload) 
django-extensions - 0.7.1  - active 
pip    - 1.0.2  - active 
setuptools  - 0.6c11  - active 
wsgiref   - 0.1.2  - active development (/usr/lib/python2.6) 
yolk   - 0.4.1  - active 

가능한 명령리스트는 runscript 명령과 함께 확장됩니다.

관련 문제