setting.py中:

 """
Django settings for untitled3 project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3p4)ob=u_tpk_ha+5fs1x8vfn+(s5-92$(05%r04ny9v+dv=qp' # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ROOT_URLCONF = 'untitled3.urls' TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
] WSGI_APPLICATION = 'untitled3.wsgi.application' # Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} # Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
] # Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/'

models.py中(数据库创建表结构都在这里):

 from django.db import models

 # Create your models here.
class Business(models.Model):
caption = models.CharField(max_length=32)
code = models.CharField(max_length=32,null=True,default='SA')#default是设置默认值,null=True是数据库中允许这个字段为空 class Host(models.Model):
nid = models.AutoField(primary_key=True) #设置主键并自增 hostname = models.CharField(max_length=32,db_index=True)#max_length设置字段最大长度 ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)#db_index=True设置为索引 port = models.IntegerField() b = models.ForeignKey(to="Business", to_field='id',on_delete=models.CASCADE)#报错加上了on_delete=models.CASCADE1
#设置外键关联Business中的id字段也可写成b = models.ForeignKey('Business',to_field='id')

urls.py中(路由都在这里):

 """untitled3 URL Configuration

 The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app01 import views
from django.conf.urls import url urlpatterns = [
path('admin/', admin.site.urls),
url(r'^business/$',views.business),#$是结束符
]

views.py中(主要业务逻辑都在这里):

 from django.shortcuts import render
from app01 import models
# Create your views here.
def business(request): v1 = models.Business.objects.all() #QuerySet
#[obj(id,caption,code),obj(id,caption,code),obj(id,caption,code)] 里面的小元素是对象 v2 = models.Business.objects.values('id', 'caption') # 拿固定列
# QuerySet
# [{'id':1,'caption':'xx','code':'da'},{....},{.....}] 里面的小元素是字典 v3 = models.Business.objects.values_list('id', 'code')
# QuerySet
# [(1,开发),(2,运维)] 里面的小元素是字典 return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3}) #注意:一定要加return 第一个参数request是对象不是字符串!不是字符串!不是字符串!

templates下的XXXX.html中(网页模板都放templates下):

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <h1> 对象 </h1>
<ul>
{% for row in v1 %} <li> {{ row.caption }}-{{ row.code }} </li> {% endfor %}
</ul> <h1> 字典 </h1> <ul>
{% for row in v2 %} <li> {{ row.id }}-{{ row.caption }} </li> {% endfor %}
</ul> <h1> 元组 </h1> <ul>
{% for row in v3 %} <li> {{ row.0}}-{{ row.1 }} </li> {% endfor %}
</ul> </body>
</html>

ORM初级实战简单的数据库交互的更多相关文章

  1. Django_简单的数据库交互案例

    https://www.jianshu.com/p/bd0af02e59ba 一.页面展示 做一个简单的数据库交换的练习案例   页面.png 二.创建mysql 表 (1)创建django (2)创 ...

  2. java实现简单的数据库的增删查改,并布局交互界面

        一.系统简介 1.1.简介  本系统提供了学生信息管理中常见的基本功能,主要包括管理员.管理员的主要功能有对学生信息进行增加.删除.修改.查找等操作,对信息进行管理,对信息进行修改.查找等操作 ...

  3. shell编程系列22--shell操作数据库实战之shell脚本与MySQL数据库交互(增删改查)

    shell编程系列22--shell操作数据库实战之shell脚本与MySQL数据库交互(增删改查) Shell脚本与MySQL数据库交互(增删改查) # 环境准备:安装mariadb 数据库 [ro ...

  4. MyBatis初级实战之一:Spring Boot集成

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  5. MyBatis初级实战之二:增删改查

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  6. MyBatis初级实战之四:druid多数据源

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  7. MyBatis初级实战之五:一对一关联查询

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  8. MyBatis初级实战之六:一对多关联查询

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  9. 10分钟系列:NetCore3.1+EFCore三步快速完成数据库交互

    前言 做程序开发,不管是什么语言什么数据库,其中的ORM(对象关系映射)是必不可少的,但是不管选择哪一种ORM,都需要了解其中的运行机制,配置帮助类等等. 所以很多ORM都开始进行升级封装,我们只需要 ...

随机推荐

  1. C++有关拷贝构造函数(默认/浅/深拷贝构造函数)

    拷贝结构函数顾名思义就是复制对象. 先讲一下默认拷贝函数: 默认拷贝就是直接赋值,让程序调用默认拷贝结构函数. Student p1; Student p2 = p1//或者Student p2(p1 ...

  2. JavaScript判断变量类型

    使用JavaScript变量时是无法判断出一个变量是0 还是“”的 这时可用typeof()来判断变量是string 还是number来区分0和“”, typeof(undefined) == 'un ...

  3. Python中的循环体

    一.循环 1.while语句: while 条件: 循环体 else: 当上面的条件不成立时才会执行 执行顺序:判断条件是否为真.如果为真,执行循环体,再次判断条件如果为假,执行else下代码块 2. ...

  4. Javascript的map与forEach的区别

    原理: 高级浏览器支持forEach方法语法:forEach和map都支持2个参数:一个是回调函数(item,index,list)和上下文: forEach:用来遍历数组中的每一项:这个方法执行是没 ...

  5. js获取url的参数和值的N种有效方法

    js获取url的参数和值的N种有效方法 function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[" ...

  6. js屏蔽鼠标操作

    document.body.onselectstart=document.body.oncontextmenu=function(){ return false;}

  7. 使用UserLock如何实现工作站登陆访问限制

    UserLock允许用户限制受保护账户可登陆的工作站/终端.工作站/终端限制可以通过设置或者使用特定的IP范围,计算机名/IP或组织单位实现. 对于每个工作站限制你需要指定所要限制的会话类型(默认情况 ...

  8. 跨平台移动开发phonegap/cordova 3.3全系列教程-helloworld

    1.    建立专案(cordova) 打开cmd命令行 cordova create ACESMobile aces.mobile ACES cd aces mobile 如图 2.    安装插件 ...

  9. redhat7.3忘记root密码后如何重置root密码

    redhat7系如果忘记root密码,重置密码方法与redhat6系不同! 1.开机启动系统,在grub选择启动内核项时 按‘e’进入编辑模式 2.这时看到的参数并不全,要按上下键滚动显示, 3.在l ...

  10. MySQL的四种主要存储引擎

    在数据库中存的就是一张张有着千丝万缕关系的表,所以表设计的好坏,将直接影响着整个数据库.而在设计表的时候,我们都会关注一个问题,使用什么存储引擎.等一下,存储引擎?什么是存储引擎? 什么是存储引擎? ...