【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 ...
随机推荐
- zoj 2679 Old Bill
Old Bill Time Limit: 2 Seconds Memory Limit: 65536 KB Among grandfather��s papers a bill was fo ...
- 记一次Jenkins 打包异常 ERROR: Exception when publishing, exception message [Failure]
今天早上打包一直都没有问题,突然有一次打包突然出现异常现象,如下: ERROR: Exception when publishing, exception message [Failure] Buil ...
- Linux(13):期中架构(5)--- 前端部分:keepalived高可用 & HTTPS & iptables防火墙
keepalived 高可用集群 1. keepalived服务概念说明 # 1.1 keepalived软件的作用? Keepalived软件起初是专为LVS负载均衡软件设计的, 用来管理并监控LV ...
- 图表控件Anychart常见问题
AnyChart控件是一款当前流行的数据可视化解决方案,使客户可以创建交互地.生动的图表.实时仪表和地图.同时支持Flash和HTML5显示,控件提供极好的视觉外观和配色方案能够使客户根据不同的需求设 ...
- java面
常被问到的十个 Java 面试题 每周 10 道 Java 面试题 : 面向对象, 类加载器, JDBC, Spring 基础概念 Java 面试题问与答:编译时与运行时 java面试基础1 java ...
- poj 3461 hash解法
字符串hash https://blog.csdn.net/pengwill97/article/details/80879387 https://blog.csdn.net/chaiwenjun00 ...
- 关于css虚线
今天遇到几个虚线效果,不能一下子反应过来具体属性. 一.dashed和dotted的区别 首先是dashed和dotted都是指“虚线”,但是两者显示的效果不尽相同. 从字面意思来看, dashed: ...
- 服务器Out of Memory
之前有次把图片存储在数据库,结果读取时候报错了:Out of Memory.. 图片本来不应该存储在数据库中的,消耗内存太大,既然已经这样,那就先解决问题,不改存储方式. 如果一个应用程序为了提高性能 ...
- Raft算法详解
一致性算法Raft详解 背景 熟悉或了解分布性系统的开发者都知道一致性算法的重要性,Paxos一致性算法从90年提出到现在已经有二十几年了,而Paxos流程太过于繁杂实现起来也比较复杂,可能也是以为过 ...
- Angular 组件通讯、生命周期钩子 小结
本文为原创,转载请注明出处: cnzt 文章:cnzt-p http://www.cnblogs.com/zt-blog/p/7986858.html http://www.cnblogs ...