ORM初级实战简单的数据库交互
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初级实战简单的数据库交互的更多相关文章
- Django_简单的数据库交互案例
https://www.jianshu.com/p/bd0af02e59ba 一.页面展示 做一个简单的数据库交换的练习案例 页面.png 二.创建mysql 表 (1)创建django (2)创 ...
- java实现简单的数据库的增删查改,并布局交互界面
一.系统简介 1.1.简介 本系统提供了学生信息管理中常见的基本功能,主要包括管理员.管理员的主要功能有对学生信息进行增加.删除.修改.查找等操作,对信息进行管理,对信息进行修改.查找等操作 ...
- shell编程系列22--shell操作数据库实战之shell脚本与MySQL数据库交互(增删改查)
shell编程系列22--shell操作数据库实战之shell脚本与MySQL数据库交互(增删改查) Shell脚本与MySQL数据库交互(增删改查) # 环境准备:安装mariadb 数据库 [ro ...
- MyBatis初级实战之一:Spring Boot集成
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- MyBatis初级实战之二:增删改查
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- MyBatis初级实战之四:druid多数据源
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- MyBatis初级实战之五:一对一关联查询
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- MyBatis初级实战之六:一对多关联查询
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- 10分钟系列:NetCore3.1+EFCore三步快速完成数据库交互
前言 做程序开发,不管是什么语言什么数据库,其中的ORM(对象关系映射)是必不可少的,但是不管选择哪一种ORM,都需要了解其中的运行机制,配置帮助类等等. 所以很多ORM都开始进行升级封装,我们只需要 ...
随机推荐
- 05-spring整合jdbc-jdbc模板对象JdbcTemplate
1 演示JdbcTemplate模板对象 1 导包 2 准备数据库 3 书写UserDao package www.test.dao; import java.util.List; import ww ...
- DEDECMS v5.7 完美实现导航条下拉二级菜单
一.引言 好多人都问,织梦的下拉导航怎么做呢?其实很简单!即使你对代码一点也不熟悉,没关系! 按照我的步骤走!记住一步也不能错哦! 二.实现过程 1.首先: 将下面这段代码贴到templets\def ...
- 【Ionic】---Using Local Notifications In Your Ionic Framework App
Using Local Notifications In Your Ionic Framework App 配置好ng-cordova先 <script src="lib/ngCord ...
- java.lang.ArrayIndexOutOfBoundsException: 160
项目突然出现这个问题java.lang.ArrayIndexOutOfBoundsException: 160,找了好大半天没有找出来哪里的问题,最后发现时fastjson.jar 版本太低了造成的, ...
- linq 两个字段排序
在linq中排序方法有: OrderBy() --对某列升序排序 ThenBy() --某列升序后对另一列后续升序排序 OrderByDescending() --对某列降序排序 ThenBy ...
- FTL(FreeMarker)基础
FreeMarker标签使用一.FreeMarker模板文件主要有4个部分组成1.文本,直接输出的部分2.注释,即<#--...-->格式不会输出3.插值(Interpolation):即 ...
- elasticsearch排序-----5
我们之前查询出的结果都会有一个_score分值表示列出结果与搜索结果的相关性,该值越高排序位置越靠前,es具体是如何计算该值的,我们认真来看看. 1.根据字段值排序 比如我们要查询/index5下su ...
- Vue Element-ui 框架:路由设置 限制文件类型 表单验证 回车提交 注意事项 监听事件
1.验证上传文件的类型: (1)验证图片类型 <template> <el-upload class="avatar-uploader" action=" ...
- JavaScript Hacks
JavaScript Hacks,很多都是在网上看到的,觉得好就记下来了.在这里给大家推荐一个项目,里面很多代码片段都值得学习https://github.com/Chalarangelo/30-se ...
- atom markdown转换PDF 解决AssertionError: html-pdf: Failed to load PhantomJS module
atom编辑器markdown转换PDF 解决AssertionError: html-pdf: Failed to load PhantomJS module. You have to set th ...