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. 在Application_Error获取Asp.Net未处理异常信息

    在Application_Error获取Asp.Net未处理异常信息 protected void Application_Error(object sender, EventArgs e) { // ...

  2. java学习第十五天

    1:对象数组(掌握) (1)数组既可以存储基本数据类型,也可以存储引用类型.它存储引用类型的时候的数组就叫对象数组. (2)案例: 用数组存储5个学生对象,并遍历数组. 2:集合(Collection ...

  3. 网页设计和制作,数学,access 2010

    网页设计和制作 插入特殊字符:插入---字符---其他字符---选择字符---完成. 插入水平线:插入---字符---水平线---右键---选择第二个框---改变颜色---完成. 插入项目类表:选择要 ...

  4. DIV+CSS图片不间断滚动jquery特效(Marquee插件)及移动标签marquee整理

    推荐一个jQuery的无缝文字滚动效果,同时也可以滚动图片,也叫做跑马灯效果. 此jquery插件,依托jquery库,能实现各种滚动效果,且让HTML代码符合W3C标准. marquee标签:创建一 ...

  5. Python开发环境Wing IDE之Search in Files工具详解

    Search in Files工具是Wing IDE中最强大的搜索选项.它支持磁盘.项目,打开编辑器,或其它文件集的多文件批量搜索.它还可以使用通配符搜索,并可以做基于正则表达式的搜索/替换. 建议用 ...

  6. 线程队列queue

    队列queue 队列用于线程之间安全的信息交换 队列和列表的区别:队列里的信息get()后就没了,而列表获取数据则是copy,原列表里的值还在 使用前先实例化队列 q = queue.Queue(ma ...

  7. oracle11g在CentOS6.9上启动脚本

    #!/bin/bash# chkconfig:2345 99 10# description: Startup Script for oracle Database# /etc/init.d/orac ...

  8. PHP : url中出现乱码问题

    例子: 在html中,将数据传到url中 当我点击“提交回复”后,跳转页面中将显示: 我们获取这个参数: 但是由于传过来的参数是中文,url会进行自动的解析成二进制的代码,那我们后台接受到的数据是解析 ...

  9. php:定义时间跳转到指定页面

    我们想要定义延迟时间,再跳转到指定页面,只要用header()即可,语法: header("Refresh:延迟时间;url=要跳转的页面"); 例子: 注意注意:我们在heade ...

  10. ARM实验2 —— 蜂鸣器实验

    PWM蜂鸣器实验: 实验内容: 编写PWM模块程序,通过PWM控制FS_4412平台上的蜂鸣器. 实验目的: 熟悉开发环境. 掌握exynos4412处理器的PWM功能. 实验平台: FS_4412开 ...