如何独立使用django的数据库访问功能

来源:互联网 发布:mac 远程 编辑:程序博客网 时间:2024/05/17 22:49

1. 安装Django

cd Django-1.4python setup.py install


2. 安装postgresql的客户端:

sudo apt-get install -y postgresql-client-9.1 python-psycopg2


3. 新建project:

django-admin.py startproject myproject

4. 在myproject下新建app:

python manage.py startapp myapp

4. 新增环境变量:

    编辑/etc/profile文件,在末尾加入以下语句:

    export PYTHONPATH=$PYTHONPATH:/home/yc/src/myproject    export DJANGO_SETTINGS_MODULE=myproject.settings

5. 假设数据库已经由Django的另一个应用(名称为otherapp)建好,数据库类型是postgresql,名称为mydb,位于192.168.1.23。见好的数据库中有一个表,名称是otherapp_user,则将otherapp/models.py拷贝到myapp/models.py。

注意检查models.py下的class user类的class Meta:部分,如果没有applabel标签,则要加上:app_label='otherapp'

再修改/home/yc/src/myproject下的settings.py文件,如下:

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.        'NAME': 'mydb',                                 # 'vps2db_test1' Or path to database file if using sqlite3.        'USER': 'postgres',                                 # Not used with sqlite3.        'PASSWORD': '123',                               # Not used with sqlite3.        'HOST': '192.168.1.23',                              # Set to empty string for localhost. Not used with sqlite3.        'PORT': '5432',                                     # Set to empty string for default. Not used with sqlite3.    }}
INSTALLED_APPS = (    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.sites',    'django.contrib.messages',    'django.contrib.staticfiles',    'myapp',) 
6. 在myapp目录下编写测试程序

from models import userif __name__=="__main__":    try:        u = user.objects.get(id=user_id)    except user.DoesNotExist:        print "user not exist)        return None    else:        return u

原创粉丝点击