1. Creating app

$ python manage.py startapp polls

That’ll create a directory polls,
which is laid out like this:

polls/
__init__.py
admin.py
migrations/
__init__.py
models.py
tests.py
views.py
1.1 Edit polls/models.py:
from django.db import models

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
  def __str__(self):              # __unicode__ on Python 2
return self.question_text
  def was_published_recently(self):
return self.pub_date >= timezone.now()

class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)

    def __str__(self):              # __unicode__ on Python 2
     return self.choice_text
1.2 Edit the mysite/settings.py file again, and change the INSTALLED_APPS setting to include the string 'polls':

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
)
1.3 Now Django knows to include the polls app. Let’s run another command:

$ python manage.py makemigrations polls
1.4    Now, run migrate again to create those model tables in your database:
       1.4.1   python manage.py check;
      1.4.2  python manage.pymigrate
1.5    

Playing with the API

1.5.1 python manage.py shell
 
1.5.2
>>> from polls.models import Question, Choice   # Import the model classes we just wrote.

# No questions are in the system yet.
>>> Question.objects.all()
[] # Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new? ", pub_date=timezone.now()) # Save the object into the database. You have to call save() explicitly.
>>> q.save() # Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> q.id
1 # Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>) # Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save() # objects.all() displays all the questions in the database.
>>> Question.objects.all()
[<Question: Question object>]


>>> from polls.models import Question, Choice

# Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What's up?>] # Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up? >] # Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?> # Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist. # Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up? > # Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True # Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1) # Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[] # Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0) # Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up? > # And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3 # The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] # Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()

【2】按照Django官网,创建一个web app 创建app/创建相应的数据库表的更多相关文章

  1. 如何搭建一个WEB服务器项目(二)—— 对数据库表进行基本的增删改查操作

    使用HibernateTemplate进行增删改查操作 观前提示:本系列文章有关服务器以及后端程序这些概念,我写的全是自己的理解,并不一定正确,希望不要误人子弟.欢迎各位大佬来评论区提出问题或者是指出 ...

  2. C#Web从0到1—创建一个web并从VS集成的SQLlocalDB数据库中查询数据

    软件说明: VS2017,腾讯云服务器10元1个月,系统Win2012 R2标准版 第一步:建立第一个网页 建立工程 建好后,可以打开View选项打开项目资源浏览器和工具箱,后文会多次用到这两个版面 ...

  3. Intellij Idea 创建一个Web项目

    今天想用IDEA创建一个web项目: 准备工具 1.jdk1.7 2.tomcat6.0,由于下载的8.5没有lib目录不能配置改6.0 3.idea2019.1.2 Intellij Idea的安装 ...

  4. C#中自己动手创建一个Web Server(非Socket实现)

    目录 介绍 Web Server在Web架构系统中的作用 Web Server与Web网站程序的交互 HTTPListener与Socket两种方式的差异 附带Demo源码概述 Demo效果截图 总结 ...

  5. eclipes创建一个web项目web.xml不能自动更新的原因(web.xml和@WebServlet的作用)

    在eclipse中创建一个Web项目的时候,虽然有web.xml生成,但是再添加Servlet类文件的时候总是看不见web.xml的更新,所以异常的郁闷!上网查了查,原来我们在创建Web项目的时候,会 ...

  6. 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】

    Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...

  7. 【重点突破】——使用Express创建一个web服务器

    一.引言 在自学node.js的过程中有一个非常重要的框架,那就是Express.它是一个基于NodeJs http模块而编写的高层模块,弥补http模块的繁琐和不方便,能够快速开发http服务器.这 ...

  8. 【LINUX】——linux如何使用Python创建一个web服务

    问:linux如何使用Python创建一个web服务? 答:一句话,Python! 一句代码: /usr/local/bin/python -m SimpleHTTPServer 8686 > ...

  9. Spring MVC 学习笔记2 - 利用Spring Tool Suite创建一个web 项目

    Spring MVC 学习笔记2 - 利用Spring Tool Suite创建一个web 项目 Spring Tool Suite 是一个带有全套的Spring相关支持功能的Eclipse插件包. ...

  10. 十七、创建一个 WEB 服务器(一)

    1.Node.js 创建的第一个应用 var http=require("http") http.createServer(function (req,res) { res.wri ...

随机推荐

  1. Python --链接Mongodb

    # -*- coding: UTF-8 -*- from pymongo import MongoClient # 数据库连接 class MongoDB(object): def __init__( ...

  2. POJ 2155 Matrix【二维线段树】

    题目大意:给你一个全是0的N*N矩阵,每次有两种操作:1将矩阵中一个子矩阵置反,2.查询某个点是0还是1 思路:裸的二维线段树 #include<iostream>#include< ...

  3. ElasticSearch索引自定义类型

    ES可以自动检测字段并设置映射类型.如果设置的索引类型不是我们所需要的,我们可以自行定义. Rest API设置自定义索引 首先通过ES自动映射一个IP地址的字段的类型: <pre name=& ...

  4. 安卓解析JSON文件

    安卓解析JSON文件 根据JOSN文件的格式,文件只有两种数据,一是对象数据,以 {}为分隔,二是数组,以[]分隔 以下介绍安卓如何解析一个JSON文件,该文件存放在assets目录下,即:asset ...

  5. Rmq Problem

    大视野——3339: Rmq Problem Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 1192  Solved: 620[Submit][Sta ...

  6. JDBC自定义连接池

    开发中,"获得连接"和"释放资源"是非常消耗系统资源的,为了解决此类性能问题可以采用连接池技术来共享连接Connection. 1.概述 用池来管理Connec ...

  7. @InsertProvider 根据bean属性,自动生成插入sql语句

    以Test为例,用mybatis的@InsertProvider的注解插入数据的时候,每次都要写类似于 Mapper类 @Mapper public interface TestDao { @Inse ...

  8. dropwatch 网络协议栈丢包检查利器 与 火丁笔记

    http://blog.yufeng.info/archives/2497 源码:http://git.fedorahosted.org/cgit/dropwatch.git http://blog. ...

  9. Linux Kernel - Debug Guide (Linux内核调试指南 )

    http://blog.csdn.net/blizmax6/article/details/6747601 linux内核调试指南 一些前言 作者前言 知识从哪里来 为什么撰写本文档 为什么需要汇编级 ...

  10. widows 2008 同步时间命令

    由于windows2008没有提供类似XP的自动同步功能,因此需要使用windows 2008计划任务来运行一行命令进行同步.   首先查看与想要同步时间的internet时间服务器的时差: w32t ...