Chinaunix首页 | 论坛 | 博客
  • 博客访问: 197003
  • 博文数量: 62
  • 博客积分: 725
  • 博客等级: 上士
  • 技术积分: 746
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-09 17:07
个人简介

exyz

文章分类

全部博文(62)

分类: Web开发

2015-02-01 11:11:35

命令行颜色
修改的配置的颜色

点击(此处)折叠或打开

  1. 第一个Django应用,数据库模型

  2.     创建一个基本的投票应用,包括2个部分:能够投票,管理站点能增加、修改和删除投票项。
  3.     该内容适合于 Django 1.7 和 Python 3.2 或更高版本。
  4.     如果Python版本是2.7,需要做稍微调整。(我安装的就是2.7.8,- -!
  5.     
  6. 1.创建项目
  7.     如果是第一次使用Django,那么需要建立一个django项目来自动生成一些代码,django的实例设置集,包括数据库配置,django的特定选项和特定设置。
  8.     
  9.     #run as root
  10.     mkdir /django
  11.     chown -R normal-user.normal-user /django
  12.     #as normal-user,进入保存代码的目录(cd /django),然后运行下面的命令:
  13.     django-admin.py startproject exyz
  14.     
  15.         会在当前目录建立 exyz 目录,项目名为“exyz”,应避免和django内置项目和组件,比如django和test的名字。
  16.         startproject 开启项目的结构:
  17.             exyz/                    #项目容器根目录,它的名字可以和项目不一致,可以重命名
  18.                 manage.py            #命令行工具,能和django项目进行交互,详细:https://docs.djangoproject.com/en/1.7/ref/django-admin/
  19.                 exyz/                #项目Python包的位置,这个目录名字是项目的名字,导入里面内容方式:exyz.urls 。
  20.                     __init__.py        #空文件,告诉Python这个目录是Python包,详细:http://docs.python.org/tutorial/modules.html#packages
  21.                     settings.py        #项目的设置和配置,详细:http://docs.python.org/tutorial/modules.html#packages
  22.                     urls.py            #URL 规则,详细:https://docs.djangoproject.com/en/1.7/topics/http/urls/
  23.                     wsgi.py            #兼容WSGI的web服务的空指针,服务于项目,详细:https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/

  24. 2.数据设置
  25.     默认使用的数据库是SQLite,适合新手用。                    
  26.     偷懒就用这个吧,没有改过,如果使用非sqlite,还要事先创建好数据库:
  27.         DATABASES = {
  28.             'default': {
  29.                 'ENGINE': 'django.db.backends.sqlite3',
  30.                 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
  31.             }
  32.         }    
  33.     时区设置,这样就会获取系统时间,啦啦啦:
  34.         TIME_ZONE = ''
  35.     INSTALLED_APPS 设置,应用能在多个项目中使用,如果可以被打包和发布的话。    
  36.         django.contrib.admin – 管理站点.
  37.         django.contrib.auth – 认证系统.
  38.         django.contrib.contenttypes – 内容类型框架.
  39.         django.contrib.sessions – session框架
  40.         django.contrib.messages – 消息框架.
  41.         django.contrib.staticfiles – 管理静态文件的框架.
  42.     这些应用默认是使用在一个常规的项目中。这些应用一部分至少使用一个数据表,所以使用之前要手动创建。
  43.     #migrate 命令查找 exyz/settings.py INSTALLED_APPS 里的设置来创建需要的表,    
  44.     python manage.py migrate
  45.     if promot " no mudule named_sqlite3 ",then:
  46.        yum  install  sqlite-devel (libsqlite3-dev python-dev )  
  47.        pip install pysqlite
  48.     
  49.     SQLite语法
  50.         sqlite3 db.sqlite3     打开sqlite文件
  51.         .databases                数据库列表
  52.         .tables                    显示表
  53.         如何从sqlite导出数据呢?
  54.             sqlite3 some.db .sch > schema
  55.             sqlite3 some.db .dump > dump
  56.             grep -v -f schema dump > data
  57.             sqlite3 -init initf db.sqlite3 .schema > schema.sql     ;db.sqlite3 是sqlite文件,schema.sql是导出的sql语句 

  58.     #启动项目,以后默认涉及 manage.py 的命令都是在 /django/exyz 目录下执行,默认指定监听本地ip和端口8000
  59.     python manage.py runserver
  60.     python manage.py runserver 8080
  61.     python manage.py runserver 0.0.0.0:8000
  62.     【切记,django只是一个框架,切勿使用于生产环境中。】
  63.     *** django 会自动加载runserver,修改代码之后不需要重启,但是添加文件需要重启。

  64. 3.创建模型
  65.     环境建好了-即项目,下面开始创建应用了。每个应用的基本结构都是由django工具创建的。
  66.     应用的位置可以放在setting里面设置的任何搜索路径中,我们放在和manage.py同级的目录中,这样可以作为它的最高级别的模型,而不是exyz的子模型。
  67.     #切换到 manage.py 的同级目录中
  68.     python manage.py startapp polls

  69.     创建应用的最初是为数据库定义模型,数据结构和必要的元数据。
  70.     投票应用中使用2个模型:Question 和 Choice。
  71.         Question 有问题和发布时间;Choice 有2个域,选择项和投票得分。
  72.         每一个Choice和Question是相关联的。
  73.         
  74.     polls/models.py
  75.         from django.db import models

  76.         class Question(models.Model):
  77.             question_text = models.CharField(max_length=200)
  78.             pub_date = models.DateTimeField('date published')

  79.         class Choice(models.Model):
  80.             question = models.ForeignKey(Question)
  81.             choice_text = models.CharField(max_length=200)
  82.             votes = models.IntegerField(default=0)
  83.     每一个模型是由类的子类呈现出来的。每一个模型都有许多类变量,每一个变量都代表这个模型的值、
  84.     每一个域是由 Field 类实例化的,CharField 是字符域, DateTimeField 是时间域,它告诉django 每个域值的数据类型。
  85.     Field 实例(比如. question_text 或 pub_date)是实例名,以机器友好的格式。
  86.     有些 Field 类需要参数,比如 CharField 需要一个 max_length ,不仅仅在数据库设计中,而且在验证中使用。
  87.     Field 还有可选参数,比如它的默认值为 0。
  88.     最后,需要定义关系,使用 ForeignKey,告诉django每一个Choice是和Question相关联的。
  89.     django支持的常见的数据关系:多对一,多对多,一对一。

  90. 4.激活数据库模型    
  91.     激活模型前,需要告诉django模型的存在。
  92.     exyz/settings.py
  93.         INSTALLED_APPS = (
  94.             'django.contrib.admin',
  95.             'django.contrib.auth',
  96.             'django.contrib.contenttypes',
  97.             'django.contrib.sessions',
  98.             'django.contrib.messages',
  99.             'django.contrib.staticfiles',
  100.             'polls',
  101.         )    
  102.     #将这个模型注册到sqlite数据库中,它的实例可以在 polls/migrations/0001_initial.py 中。
  103.     python manage.py makemigrations polls
  104.     
  105.     #migrate 可以用来迁移数据库,sqlmigrate 可以用来看到 migrate 会运行的SQL语句,只是测试不会真正运行。migrate也只是会同步没有被应用的数据库设置。
  106.     python manage.py sqlmigrate polls 0001
  107.     python manage.py migrate 

  108.       if comes "ImportError: No module named _sqlite3",then need rebuild Python,if build python without "sqlite-devel" before:
  109.       yum install sqlite-devel
  110.       build python now.. 
  111.     
  112.     #?如何测试正确与否?
  113.     python manage.py check
  114.     
  115. 5.测试数据库模型
  116.     #在manage.py目录下,下面命令会设置让 manage.py 设置 DJANGO_SETTINGS_MODULE 环境变量,让Python导入 exyz/settings.py 文件。
  117.     python manage.py shell
  118.     
  119.     #导入之前创建的模型
  120.     >>> from polls.models import Question, Choice
  121.     #显示所有数据
  122.     >>> Question.objects.all()
  123.     
  124.     #使用数据模型
  125.     >>> from django.utils import timezone
  126.     >>> q = Question(question_text="What's new?", pub_date=timezone.now())
  127.     >>> q.save()
  128.     >>> q.id
  129.     >>> q.question_text
  130.     >>> q.pub_date
  131.     >>> q.question_text = "What's up?"
  132.     >>> q.save()
  133.     >>> Question.objects.all()

  134.     #为了修改django的数据类型,下面文件需要添加些新的内容:
  135.     polls/models.py
  136.         from django.db import models

  137.         class Question(models.Model):
  138.             # ...
  139.             def __str__(self): # __unicode__ on Python 2
  140.                 return self.question_text

  141.         class Choice(models.Model):
  142.             # ...
  143.             def __str__(self): # __unicode__ on Python 2
  144.                 return self.choice_text
  145.     #添加自定义方法
  146.     polls/models.py
  147.         import datetime

  148.         from django.db import models
  149.         from django.utils import timezone


  150.         class Question(models.Model):
  151.             # ...
  152.             def was_published_recently(self):
  153.                 return self.pub_date >= timezone.now() - datetime.timedelta(days=1)    

  154.     #使用数据模型
  155.     python manage.py shell
  156.     >>> from polls.models import Question, Choice
  157.     >>> Question.objects.all()
  158.     >>> Question.objects.filter(id=1)
  159.     >>> Question.objects.filter(question_text__startswith='What')
  160.     >>> from django.utils import timezone
  161.     >>> current_year = timezone.now().year
  162.     >>> Question.objects.get(pub_date__year=current_year)
  163.     >>> Question.objects.get(id=2)
  164.     >>> Question.objects.get(pk=1)
  165.     >>> q = Question.objects.get(pk=1)
  166.     >>> q.was_published_recently()
  167.     >>> q = Question.objects.get(pk=1)
  168.     >>> q.choice_set.all()
  169.     >>> q.choice_set.create(choice_text='Not much', votes=0)
  170.     >>> q.choice_set.create(choice_text='The sky', votes=0)
  171.     >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
  172.     >>> c.question
  173.     >>> q.choice_set.all()
  174.     >>> q.choice_set.count()
  175.     >>> Choice.objects.filter(question__pub_date__year=current_year)
  176.     >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
  177.     >>> c.delete()

阅读(1789) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~