Django学堂在线笔记-1

news/2025/1/22 10:28:15/

1. 基本命令-扫盲向

a 新建一个项目后添加一个app(name: myapp for instance)

python">python manage.py startapp myapp

b 启动服务

python">python manage.py runserver

2. 复杂模版及变量传递

views.py

python">from django.shortcuts import renderfrom tem_app.Person import Person# Create your views here.
def tem_var(request, name):return render(request, "show_var.html", {"name": name})def pass_dict(request):product1 = {"name": "Django","teacher": "李老师"}return render(request, "show_info.html", {"product": product1})def pass_obj(request):p = Person("李文鹏", 18)return render(request, "show_info.html", {"person": p})def pass_list(request):fruits = ["apple", "banana"]return render(request, "show_info.html", {"fruits": fruits})def pass_all(request):product1 = {"name": "Django","teacher": "李老师"}p = Person("李文鹏", 18)fruits = ["apple", "banana"]# return render(request, "show_info.html", {"product": product1, "person": p, "fruits": fruits}) # method1 for logic explain""""locals = {"request": request   # 也传递了一个request对象,具体原因下次再说"fruits": fruits,"product": product1,"p": p}"""return render(request, "show_info.html", locals()) # method2: use locals() object

tem_app/urls.py 

python">"""
URL configuration for hw2 project.The `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views1. Add an import:  from my_app import views2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views1. Add an import:  from other_app.views import Home2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf1. Import the include() function: from django.urls import include, path2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""from django.urls import pathfrom tem_app.views import pass_dict, tem_var, pass_obj, pass_list, pass_allurlpatterns = [# path("admin/", admin.site.urls),path("var/<name>/", tem_var),path("dict/", pass_dict), # 传递字典path("obj/", pass_obj),  # 传递对象path("list/", pass_list), # 传递列表path("all/", pass_all)
]

3. 模版标签

a 简单if标签

{% if 布尔值 %}

布尔值为True时,显示的内容

{% else %}

布尔值为False时,显示的内容

{% endif %}

b 多分支if标签

{% if score >= 90  %}

优秀

{% if score >= 80  %}

良好

{% if score >= 60  %}

一般

{% else  %}

不合格

{% endif %}

c for标签
python">{% for fruit in fruits %}<li> {{ fruit }}</li>{% endfor %}

tag_for.html

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>for标签</title></head><body><ul>{% for fruit in fruits %}<li> {{ forloop.counter }} {{ fruit }}</li>{%  empty %}<h3> 什么都没有 </h3>{% endfor %}<hr>{% for item in items %}{{ item }}{% if not forloop.last %}|{% endif %}{% endfor %}<h4> Reversed order of items: </h4>{% for item in items reversed %}{{ item }}{% if not forloop.last %}|{% endif %}{% endfor %}<hr></ul></body></html>
d include标签

{% include '包含的模版地址' %}

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>include标签</title>
</head>
<body>
欢迎访问我栋网站<br>
网站内容<br><hr>
{% include 'footer.html' %}
</body>
</html>

footer.html

友情链接: <a href="http://www.baidu.com"> 百度 </a> <br>
<a href="http://www.360.com"> 360 </a> <br>
<a href="http://www.sogou.com"> 搜狗 </a> <br>
<a href="http://121.40.143.58"> 多米的空中小屋 </a> <br>
<a href="http://www.sohu.com"> 搜狐 </a> <br>
联系电话:18010000000
e 模版继承标签

子模板:{% entends  父模版位置 %}

父模版:

        {% block 块名称 %}

        {% endblock %}

模版过滤器 

{{ 模版变量 | 过滤器 }}

自定义模版过滤器

python">from django import templateregister = template.Library()@register.filter(name="abc")
def upper_number(value: int):try:return ["〇", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾"][value]except IndexError:return "Error Params"

4. Django基础模型

4.1 mysql相关-基础

a 增

添加数据的两种方式

1. 通过对象管理器添加

python">Students.objects.add(name="梓潼", gender="男", score=12)

2. 通过实例化对象添加

python">s = Students(name="多米", gender="男", score=33)
s.save()

测试

python">### add data
```pythonclass StudentsTestCase(TestCase):def setUp(selfself) -> None:self.start_time = time.time()# Add datadef test_insert_data(self):# Method1: Object managerStudents.objects.create(name="test", gender="Male", score=99.5)print(f"Time Cost: {time.time() - self.start_time}")# Method2: Objectify the objects = Students(name="test", gender="Male", score="44.1")s.save()print(f"Time Cost: {time.time() - self.start_time}")def tearDown(self) -> None:print("Test Done")```
b 改删
python">s1 = Students(name="韩梅梅", gender="女", score=67)
s1.save()# modify
s1.name = "Xiaoming"
s1.save()
s1.gender="男"
s1.save()# delete
s1.delete()
# Notice: no need save

c 查

简单模糊查询

c1 通过主键查询一条记录
python"># 通过主键 primary key
s1 = Students.objects.get(pk=1)# 通过ID
s1 = Students.objects.get(id=1)

 c2 多条记录按索引访问
python">s = Students.objects.all()
# Then we will get a Students object(1)s[0].name# 即使查不到数据,返回的对象仍然是QuerySet,只是空而已
 c3 过滤查询

几个模糊查找的方式:

__contains: s = Students.objects.filter(name__contains="李")

__startswith: s = Students.objects.filter(name__startwith="韩")

__endswith: 

__gte: greater than or equal to

__lte: less than or equal to

__year

__month

__day

# python manage.py
python manage.py shell# after join mysql and the command line start with <<<
s = Students.objects.filter(name__contains="李")
s
c4 异常处理 

插播一条如果在添加join_date字段的时候报错的处理过程,这里卡了一会儿,最后解决方案是把数据库删除重置修复的,命令如下:

python">DROP DATABASE my_django;exitmysql -u root -pcreate database my_django;use my_django

然后在Django端重新操作就好了,这里可以一遍添加一边查询查看数据库的更新过程:

c5 排除查询和限制查询
# query those whose score is greater and equal than --
s = Students.objects.filter(score__gte=80)
for i in s:print(i.name)print(i.score)s = Students.objects.exclude(score__gte=80)
s
# output are like: <QuerySet []>s = Students.objects.all()
c6 排序查询

c7 原生查询 raw()

可以再Django中直接嵌入mysql原生语句的查询方式

all_1 = Students.objects.all()
all = Students.objects.raw("select * from students;")a = Students.objects.raw("select id, name from students where name like 't%%';")
for i in a:print(i.name)s = Students.objects.raw("select * from students where name=%s and gender=%s", ["韩梅梅", "女"])
for i in s:print(i.name, "--", i.gender)# generate migration script
python manage.py makemigrations

c8 Q查询

用于比较复杂的组合关系查询,filter查询不太好用的时候使用,首先注意需要先import Q!

下面是查询q1成绩大于90, q2名字不是以韩开头的数据:注意名字以什么支付开始的判断是startswith

s_all = Students.objects.all()
[i.name for i in s_all]
# Query those score is > 80 and in start with "韩"

c9 F查询

同样要先导入F查询的包

c10 聚合查询

要对数据做一些聚合运算,统计下平均值,总数等

python">from django import Sum, Avg, Max, Min, Countavg_score = Students.objects.all().aggregate(Avg("score"))
avg_score
avg_score = Students.objects.aggregate(Avg("score"))

c11 分组查询
score_avg = Students.objects.values("gender").annotate(Agv("score"))

4.2 综合演练

笔记2


http://www.ppmy.cn/news/1565199.html

相关文章

【优选算法】4----盛最多水的容器

开始有点上强度了铁子们&#xff0c;这道算法题也是可以说很难理解的~ 想了好久才想明白~ ---------------------------------------begin--------------------------------------- 题目解析&#xff1a; 这一道题刚看题目&#xff0c;根本不知道在讲啥&#xff0c;但看到体积…

Spring Boot拦截器:掌握Web请求的“守门员”

在Spring Boot中&#xff0c;拦截器&#xff08;Interceptor&#xff09;就像是一个门卫&#xff0c;能够在请求到达控制器之前或之后进行一些检查或操作。使用拦截器通常包含以下几个步骤&#xff1a; 1. 定义拦截器 首先&#xff0c;你需要创建一个拦截器类&#xff0c;这个…

【大数据】关于机器学习----------规则学习

一、基本概念 注&#xff1a;本博文所含流程图引用知乎博主 deephub 1. 规则学习 规则学习是从数据中自动提取出能表示数据规律的规则的机器学习方法。这些规则通常以 if-then 形式出现&#xff0c;可用于分类、预测和决策等任务。例如&#xff1a;if (feature1 > 5) and (…

如何运行第一个Tomcat HttpServlet 程序

怀旧网个人博客网站地址&#xff1a;怀旧网&#xff0c;博客详情&#xff1a;如何运行第一个Tomcat HttpServlet 程序 1、编写一个 Servlet 类 创建一个包 在创建一个类--继承HttpServlet 爆红&#xff1a;原因&#xff0c;没有导入所依赖的包 altenter 选着add macen 选着第…

自动化标注平台开源,基于 yolov8标注平台可本地部署

yolov8标注平台本地部署&#xff08;docker部署&#xff09;&#xff0c;已调通yolov8模型自动预标注功能。 下面开始背景知识…… 1&#xff09;数据标注为什么在人工智能时代如此重要&#xff1f; 数据标注在人工智能时代如此重要&#xff0c;原因如下&#xff1a; 为机器…

tcpdump 精准分析vxlan网络

一、相关概念 ​ VXLAN&#xff08;Virtual eXtensible Local Area Network&#xff0c;虚拟扩展局域网&#xff09;&#xff0c;是由IETF定义的NVO3&#xff08;Network Virtualization over Layer 3&#xff09;标准技术之一&#xff0c;是对传统VLAN协议的一种扩展。VXLAN的…

PyQt5 超详细入门级教程上篇

PyQt5 超详细入门级教程 上篇&#xff1a;1-3部分&#xff1a;PyQt5基础与常用控件 第1部分&#xff1a;初识 PyQt5 和安装 1.1 什么是 PyQt5&#xff1f; PyQt5 是 Python 的图形用户界面 (GUI) 框架&#xff0c;它基于强大的 Qt 库。Qt 是一个跨平台的 C 框架&#xff0c;用…

七.网络模型

最小(支撑)树问题 最小部分树求解&#xff1a; 破圈法&#xff1a;任取一圈&#xff0c;去掉圈中最长边&#xff0c;直到无圈&#xff1b; 加边法&#xff1a;取图G的n个孤立点&#xff5b;v1&#xff0c;v2&#xff0c;…&#xff0c; vn }作为一个支撑图&#xff0c;从最短…