Django学堂在线笔记-1

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 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

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 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标签
python 复制代码
{% for fruit in fruits %}
            <li> {{ fruit }}</li>
        {% endfor %}

tag_for.html

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 '包含的模版地址' %}

html 复制代码
<!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

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 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. 通过对象管理器添加
python 复制代码
Students.objects.add(name="梓潼", gender="男", score=12)
  1. 通过实例化对象添加
python 复制代码
s = Students(name="多米", gender="男", score=33)
s.save()

测试

python 复制代码
### 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 改删
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

bash 复制代码
# 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;

exit

mysql -u root -p

create database my_django;

use my_django

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

c5 排除查询和限制查询
bash 复制代码
# 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原生语句的查询方式

bash 复制代码
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名字不是以韩开头的数据:注意名字以什么支付开始的判断是starts with

bash 复制代码
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, 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

相关推荐
汇能感知12 小时前
摄像头模块在运动相机中的特殊应用
经验分享·笔记·科技
阿巴Jun12 小时前
【数学】线性代数知识点总结
笔记·线性代数·矩阵
zhousenshan13 小时前
Python爬虫常用框架
开发语言·爬虫·python
茯苓gao13 小时前
STM32G4 速度环开环,电流环闭环 IF模式建模
笔记·stm32·单片机·嵌入式硬件·学习
是誰萆微了承諾13 小时前
【golang学习笔记 gin 】1.2 redis 的使用
笔记·学习·golang
IMER SIMPLE13 小时前
人工智能-python-深度学习-经典神经网络AlexNet
人工智能·python·深度学习
CodeCraft Studio13 小时前
国产化Word处理组件Spire.DOC教程:使用 Python 将 Markdown 转换为 HTML 的详细教程
python·html·word·markdown·国产化·spire.doc·文档格式转换
DKPT14 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
ST.J14 小时前
前端笔记2025
前端·javascript·css·vue.js·笔记
专注API从业者14 小时前
Python/Java 代码示例:手把手教程调用 1688 API 获取商品详情实时数据
java·linux·数据库·python