Django学堂在线笔记-1
1. 基本命令-扫盲向
a 新建一个项目后添加一个app(name: myapp for instance)
python manage.py startapp myapp
b 启动服务
python manage.py runserver
2. 复杂模版及变量传递
views.py
from django.shortcuts import render
from 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
"""
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 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.urls import path
from tem_app.views import pass_dict, tem_var, pass_obj, pass_list, pass_all
urlpatterns = [
# 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标签
{% 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 %}
模版过滤器
{{ 模版变量 | 过滤器 }}
自定义模版过滤器
from django import template
register = 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. 通过对象管理器添加
Students.objects.add(name="梓潼", gender="男", score=12)
2. 通过实例化对象添加
s = Students(name="多米", gender="男", score=33)
s.save()
测试
### add data
```python
class StudentsTestCase(TestCase):
def setUp(selfself) -> None:
self.start_time = time.time()
# Add data
def test_insert_data(self):
# Method1: Object manager
Students.objects.create(name="test", gender="Male", score=99.5)
print(f"Time Cost: {time.time() - self.start_time}")
# Method2: Objectify the object
s = 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 改删
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 通过主键查询一条记录
# 通过主键 primary key
s1 = Students.objects.get(pk=1)
# 通过ID
s1 = Students.objects.get(id=1)
c2 多条记录按索引访问
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字段的时候报错的处理过程,这里卡了一会儿,最后解决方案是把数据库删除重置修复的,命令如下:
DROP DATABASE my_django;
exit
mysql -u root -p
create 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 聚合查询
要对数据做一些聚合运算,统计下平均值,总数等
from django import Sum, Avg, Max, Min, Count
avg_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