Django之--MVC的Model
在上一篇:Django之--通过MVC架构的html模板展示Hello World! 讲述了基本的MVC模型,但是却并没有测试Model的作用,本文通过mysql数据库来测试。
Django自带的model支持多数主流数据库,如MySQL、Oracle、PostgreSQL、SQLLite等,对MSSQL的支持可能不是很好,如果你自己写Model那就无所谓了。
如果你要使用Django自带的数据库Model,那么参照如下网址的步骤一步步做就可以了,本文为深入了解Model的功能以及其与view的联动(闲的蛋疼)自己写个简易的Model。(生产推荐用自带的model,BUG少兼容性好)
http://www.runoob.com/django/django-model.html
1.首先我们在数据库中插入一些数据,如下所示:
create table product(
id int auto_increment primary key,
name varchar(100) comment "商品名称",
price decimal(10,2) comment "商品价格",
quantity int comment "商品当前保有量"
);
insert into product(name,price,quantity) values('铅笔',1.00,100),('橡皮',0.5,200),('钢笔',5.00,50),
('复读机',200,10),('手机',2399,20);
# -*- coding: utf-8 -*-
from MySQLdb import *
config = {'host':'192.168.1.193','port':3306,'user':'leo','password':'mysql','db':'test','charset':'utf8'}
def db_modify(sql):
try:
conn = Connect(**config)
cur = conn.cursor()
cur.execute(sql)
conn.commit()
except:
conn.rollback()
print ('SQL is not executed properly...')
finally:
conn.close()
def db_query(query_sql):
try:
conn=Connect(**config)
cur=conn.cursor()
cur.execute(query_sql)
result=cur.fetchall()
return result
except:
print ('SQL is not executed properly...')
finally:
conn.close()
3.接下来修改urls.py(MVC之Controller)
from django.conf.urls import url
from . import view,product --import product,product.py会在下一步定义,就是MVC中的View,相当于上一篇中的view.py
urlpatterns = [
url(r'^hello$', view.hello),
url(r'^product-page$', product.page), #新加项
url(r'^product-result$', product.result), #新加项
]
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render
from . import mysql
# 表单
def page(request):
context={}
context['标题'] ='商品种类:'
pro_list=mysql.db_query("select distinct name from product")
context['商品列表']=[]
for i in range(0,len(pro_list)):
context['商品列表'].append(pro_list[i][0])
return render(request,'page.html',context)
# 接收请求数据
def result(request):
request.encoding='utf-8'
pro=request.GET['q']
if not pro.strip():
message = '搜索项不能为空'
else:
price_quan=mysql.db_query("select price,quantity from product where name='%s'"%(pro))
price=str(price_quan[0][0])
quantity=str(price_quan[0][1])
message = '你搜索的商品为: ' + pro + '商品价格为:' + price + '商品余量为:' + quantity
return HttpResponse(message)
模板的位置是在/root/Django/mysite/templates下,这里添加page.html如下:
<!DOCTYPE html>
<html>
<h3>{{ 标题 }}</h3>
<body>
<p>
{% for 商品 in 商品列表 %}
<li><font face="verdana" color="blue" size=4>{{ 商品 }}</font></li>
{% endfor %}
</p>
<br>
<form action="/product-result" method="get">
<input type="text" name="q">
<input type="submit" value="查看商品信息">
</form>
</body>
</html>
开启Django Server:python3 manage.py runserver 0.0.0.0:8000
最终的展示效果如下:


Django之--MVC的Model的更多相关文章
- MVC(Model View Controller)框架
MVC框架 同义词 MVC一般指MVC框架 MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一 ...
- Django之MVC框架与MTV框架详解
Django框架简介 MVC框架和MTV框架(了解即可) MVC,全名是Model View Controller,是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model).视图 ...
- Django之MVC和MTV
一. MVC MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建 Web 应用程序的模式: Model(模型)表示应用程序核心(比如数据库记录列表). ...
- 第一章 Django之MVC模式(2)
让我们来研究一个简单的例子,通过该实例,你可以分辨出,通过 Web 框架来实现的功能与之前的方式有何不同.下面就是通过使用 Django 来完成以上功能的例子: # models.py (the da ...
- Asp.net MVC使用Model Binding解除Session, Cookie等依赖
上篇文章"Asp.net MVC使用Filter解除Session, Cookie等依赖"介绍了如何使用Filter来解除对于Session, Cookie的依赖.其实这个也可以通 ...
- Asp.net MVC的Model Binder工作流程以及扩展方法(2) - Binder Attribute
上篇文章中分析了Custom Binder的弊端: 由于Custom Binder是和具体的类型相关,比如指定类型A由我们的Custom Binder解析,那么导致系统运行中的所有Action的访问参 ...
- Asp.net MVC的Model Binder工作流程以及扩展方法(1) - Custom Model Binder
在Asp.net MVC中, Model Binder是生命周期中的一个非常重要的部分.搞清楚Model Binder的流程,能够帮助理解Model Binder的背后发生了什么.同时该系列文章会列举 ...
- MVC中Model用法
Model:对于MVC来说,Model可不简单只是实体,它应该叫视图模型,这是我自己的理解,即视图中的数据由Model来提供,当视图的数据需要改变时,我们不用打开aspx或ascx文件,只需要修改相应 ...
- MetadataType的使用,MVC的Model层数据验证
MetadataType的使用,MVC的Model层数据验证 指定要与数据模型类关联的元数据类 using System.ComponentModel.DataAnnotations; //指定要 ...
随机推荐
- 【API知识】RestTemplate的使用
前言 在某种情况下,后台服务可能需要访问另一台服务器的REST接口.以前估计不少人用的都是HttpRequest类来着,结合Paser解析JSON格式的Body.现在Spring Boot的Web S ...
- 10分钟学会使用YOLO及Opencv实现目标检测(下)|附源码
将YOLO应用于视频流对象检测 首先打开 yolo_video.py文件并插入以下代码: # import the necessary packages import numpy as np impo ...
- HBase 架构脑图
https://docs.transwarp.io/5.0/goto?file=HyperbaseManual_intro-hbase.html#intro-hbase
- webservice的两种调用方式
如下 using ConsoleApplication1.TestWebService; using System; using System.Collections; using System.Co ...
- You must reset your password using ALTER USER statement before executing this statement.
MySQL 5.7之后,刚初始化的MySQL实例要求先修改密码.否则会报错: mysql> create database test; ERROR 1820 (HY000): You must ...
- SSM框架的sql中参数注入(#和$的区别)
<select id="findUsersByUserName2" resultType="java.util.Map" parameterType=&q ...
- 跨域学习笔记1--跨域调用webapi
在做Web开发中,常常会遇到跨域的问题,到目前为止,已经有非常多的跨域解决方案. 通过自己的研究以及在网上看了一些大神的博客,写了一个Demo 首先新建一个webapi的程序,如下图所示: 由于微软已 ...
- 将ASP.NET网站部署到服务器IIS上
ASP.NET编写的网站程序,在网站编写完成所有流程都测试通过后,需要将网站发布到IIS的Web服务器上,此文将介绍发布的流程以及IIS相关设置过程,帮助读者了解网站发布的流程. 一.首先在Visua ...
- python面向对象学习(四)继承
目录 1. 单继承 1.1 继承的概念.语法和特点 1.2 方法的重写 1.3 父类的 私有属性 和 私有方法 2. 多继承 2.1 多继承的使用注意事项 2.2 新式类与旧式(经典)类 1. 单继承 ...
- 学习记录(一)之h5_canvas
canvas(画布) canvas(画布): 利用JS在网页中绘制图像. 标签:<canvas></canvas> 属性:height,width(宽高属性要写在行内样式中); ...