【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 ...
随机推荐
- Leetcode 397.整数替换
整数替换 给定一个正整数 n,你可以做如下操作: 1. 如果 n 是偶数,则用 n / 2替换 n.2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n.n 变为 1 所需的最小替换次数是 ...
- 九度oj 题目1160:放苹果
题目描述: 把M个同样的苹果放在N个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?(用K表示)5,1,1和1,5,1 是同一种分法. 输入: 第一行是测试数据的数目t(0 <= t ...
- iOS第三方-百度地图地图SDK(一)
前言 最近项目忙完了准备把百度地图的方法都熟悉一遍,基于百度地图2.10.0,写demo的同时也写下博客来记录下 模拟器设置 我直接就复制我以前写过的一篇的图了,懒得截图... 获取百度地图KEY 让 ...
- [luoguP2495] [SDOI2011]消耗战(DP + 虚树)
传送门 明显虚树. 别的题解里都是这样说的. 先不考虑虚树,假设只有一组询问,该如何dp? f[u]表示把子树u中所有的有资源的节点都切掉的最优解 如果节点u需要切掉了话,$f[u]=val[u]$ ...
- haskell 乱搞笔记[原创]
脑洞时间:为什么世界上有那么多程序语言,那是腐朽的资本主义为了增加广大人民学习成本以及编译原理太过普及造成的,建议大学取消编译原理的一切课程,并挥起奥姆休的剃刀,把所有程序语言统统踢了,除机器 ...
- 洛谷 [T21778] 过年
离线扫描线+查分+线段树 我们发现,这个题的询问都是离线的,所以我们尝试用离线扫描线的方法来处理 对于每一次操作,我们维护一个差分数组, 在询问的时候,我们用一根扫描线,从左往右扫,并用线段树维护,每 ...
- 【POJ1226】Substrings(后缀数组,二分)
题意: n<=10,len<=100 思路: 只有一个字符串的时候特判一下 #include<cstdio> #include<cstring> #include& ...
- Fabrice Bellard其人 ---- FFMPEG及其他……
有些计算机科学家的名字耳熟能详:阿兰·图灵(Alan Turing).高纳德(Donald Knuth).艾兹赫尔·戴克斯特拉(Edsger Dijkstra),这些人的名气甚至大于他们突破性的成就. ...
- docker镜像mac下保存路径
mac下docker的镜像保存位置: /Users/{YourUserName}/Library/Containers/com.docker.docker/Data/com.docker.driver ...
- nginx配置 location root alias
语法规则: location [=|~|~*|^~] /uri/ { … } = 开头表示精确匹配 ^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可.nginx不对url做编码,因 ...