【2】按照Django官网,创建一个web app 创建app/创建相应的数据库表
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_textdef 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 2return 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 shell1.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/创建相应的数据库表的更多相关文章
- 如何搭建一个WEB服务器项目(二)—— 对数据库表进行基本的增删改查操作
使用HibernateTemplate进行增删改查操作 观前提示:本系列文章有关服务器以及后端程序这些概念,我写的全是自己的理解,并不一定正确,希望不要误人子弟.欢迎各位大佬来评论区提出问题或者是指出 ...
- C#Web从0到1—创建一个web并从VS集成的SQLlocalDB数据库中查询数据
软件说明: VS2017,腾讯云服务器10元1个月,系统Win2012 R2标准版 第一步:建立第一个网页 建立工程 建好后,可以打开View选项打开项目资源浏览器和工具箱,后文会多次用到这两个版面 ...
- Intellij Idea 创建一个Web项目
今天想用IDEA创建一个web项目: 准备工具 1.jdk1.7 2.tomcat6.0,由于下载的8.5没有lib目录不能配置改6.0 3.idea2019.1.2 Intellij Idea的安装 ...
- C#中自己动手创建一个Web Server(非Socket实现)
目录 介绍 Web Server在Web架构系统中的作用 Web Server与Web网站程序的交互 HTTPListener与Socket两种方式的差异 附带Demo源码概述 Demo效果截图 总结 ...
- eclipes创建一个web项目web.xml不能自动更新的原因(web.xml和@WebServlet的作用)
在eclipse中创建一个Web项目的时候,虽然有web.xml生成,但是再添加Servlet类文件的时候总是看不见web.xml的更新,所以异常的郁闷!上网查了查,原来我们在创建Web项目的时候,会 ...
- 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 创 ...
- 【重点突破】——使用Express创建一个web服务器
一.引言 在自学node.js的过程中有一个非常重要的框架,那就是Express.它是一个基于NodeJs http模块而编写的高层模块,弥补http模块的繁琐和不方便,能够快速开发http服务器.这 ...
- 【LINUX】——linux如何使用Python创建一个web服务
问:linux如何使用Python创建一个web服务? 答:一句话,Python! 一句代码: /usr/local/bin/python -m SimpleHTTPServer 8686 > ...
- Spring MVC 学习笔记2 - 利用Spring Tool Suite创建一个web 项目
Spring MVC 学习笔记2 - 利用Spring Tool Suite创建一个web 项目 Spring Tool Suite 是一个带有全套的Spring相关支持功能的Eclipse插件包. ...
- 十七、创建一个 WEB 服务器(一)
1.Node.js 创建的第一个应用 var http=require("http") http.createServer(function (req,res) { res.wri ...
随机推荐
- ASP.NET(一):Reques对象和Response对象的区别,以及IsPostBack属性的用法
导读:在ASP.NET的学习中,初步认识了其6大对象(严格说来只能算是属性):Request,Response,Application,Session,Server,OjectContext.这些对象 ...
- 关于流媒体(m3u8)的播放与下载
前一段时间做了一个视频播放下载应用,抓取的是优酷的视频,虽然优酷有自己的开发平台http://open.youku.com/,但未真正的实现.所以只能靠抓取视频源,Youku的视频采取了加密+动态的获 ...
- POJ 1038 Bugs Integrated, Inc. ——状压DP
状态压缩一下当前各格子以及上面总共放了几块,只有012三种情况,直接三进制保存即可. 然后转移的时候用搜索找出所有的状态进行转移. #include <map> #include < ...
- [luoguP2606] [ZJOI2010]排列计数(DP)
传送门 如果能够根据题意看出这是一个堆的话,那么就有些思路了.. 首先堆顶必须是最小元素,然后左右儿子可以预处理出来都有多少个数, 把剩余的数任意分配给两个儿子,用排列组合即可 dp(now) = d ...
- LightOJ1106 Gone Fishing
Gone Fishing John is going on a fishing trip. He has h hours available, and there are n lakes in the ...
- angular中ng-repeat去重
[html] view plain copy print?在CODE上查看代码片派生到我的代码片 <div ng-app="myApp" ng-controller=&quo ...
- Spring Boot SpringSecurity5 身份验证
对于没有访问权限的用户需要转到登录表单页面.要实现访问控制的方法多种多样,可以通过Aop.拦截器实现,也可以通过框架实现(如:Apache Shiro.Spring Security). pom.xm ...
- uva 10710 快速幂取模
//题目大意:输入一个n值问洗牌n-1次后是不是会变成初始状态(Jimmy-number),从案例可看出牌1的位置变化为2^i%n,所以最终判断2^(n-1)=1(mod n)是否成立#include ...
- java连oracle
下载连接驱动 安装完oracle之后 D:\app\Administrator\product\11.2.0\dbhome_1\jdbc\lib 目录下拷贝 支持jdk1.6以上 From.java ...
- HDU 5636 Shortest Path(Floyd)
题目链接 HDU5636 n个点,其中编号相邻的两个点之间都有一条长度为1的边,然后除此之外还有3条长度为1的边. m个询问,每次询问求两个点之前的最短路. 我们把这三条边的6个点两两算最短路, 然 ...