首页 > 其他分享 >【Django】学习笔记

【Django】学习笔记

时间:2024-06-02 21:33:05浏览次数:21  
标签:models py request 笔记 BookInfo 学习 book django Django

文章目录

因上努力

个人主页:丷从心

系列专栏:Django

学习指南:【进收藏夹吃灰系列】Python学习指南

果上随缘


MVC与MTV

MVC设计模式

1

MTV设计模式

2


Django下载

pip install django==2.2.5

Django工程创建与运行

创建工程
django-admin startproject book_manager
运行工程
python manage.py runserver

子应用创建与注册安装

创建子应用
python manage.py startapp book
注册安装子应用
  • 配置settings.py中的INSTALLED_APPS
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'book.apps.BookConfig',
]

数据模型

ORM框架
  • 配置models.py
from django.db import models


# Create your models here.

# 书籍信息表
class BookInfo(models.Model):
    name = models.CharField(max_length=10, verbose_name='书籍名称')
    pub_date = models.DateField(null=True, verbose_name='出版日期')
    read_count = models.IntegerField(default=0, verbose_name='阅读量')
    comment_count = models.IntegerField(default=0, verbose_name='评论量')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'book_info'
        verbose_name = '书籍信息管理'
        verbose_name_plural = verbose_name


# 人物信息表
class PersonInfo(models.Model):
    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )

    name = models.CharField(max_length=10, verbose_name='人物名称')
    gender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='人物性别')
    description = models.CharField(max_length=100, null=True, verbose_name='人物描述')
    book = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='人物所属书籍')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'person_info'
        verbose_name = '人物信息管理'
        verbose_name_plural = verbose_name
模型迁移
  • Tools->Run manage.py Task
makemigrations
migrate

Admin站点

修改语言和时区
  • 配置settings.py
LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'
设置管理员账号密码
  • Tools->Run manage.py Task
createsuperuser
模型注册
  • 配置admin.py
from django.contrib import admin

# Register your models here.

from .models import BookInfo, PersonInfo

admin.site.register(BookInfo)
admin.site.register(PersonInfo)
显示对象名称
from django.db import models


# Create your models here.

# 书籍信息表
class BookInfo(models.Model):
    name = models.CharField(max_length=10)

    def __str__(self):
        return self.name


# 人物信息表
class PersonInfo(models.Model):
    name = models.CharField(max_length=10)
    gender = models.BooleanField()
    book = models.ForeignKey(BookInfo, on_delete=models.CASCADE)

    def __str__(self):
        return self.name
模型显示中文
from django.db import models


# Create your models here.

# 书籍信息表
class BookInfo(models.Model):
    name = models.CharField(max_length=10)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '书籍信息管理'
        verbose_name_plural = verbose_name


# 人物信息表
class PersonInfo(models.Model):
    name = models.CharField(max_length=10)
    gender = models.BooleanField()
    book = models.ForeignKey(BookInfo, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '人物信息管理'
        verbose_name_plural = verbose_name
App显示中文
  • 配置apps.py
from django.apps import AppConfig


class BookConfig(AppConfig):
    name = 'book'
    verbose_name = '书籍管理'

视图函数与路由系统

定义视图函数
  • 配置views.py
from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse


def index(request):
    return HttpResponse('OK!')
配置路由系统
  • 创建子路由:在book文件夹下建立urls.py文件
from django.urls import path
from . import views

urlpatterns = [
    path('index/', views.index),
]
  • 配置总路由
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('book.urls'))
]

模板渲染

配置模板路径
  • 在项目根路径下建立templates文件夹
  • 配置settings.py
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',
            ],
        },
    },
]
  • templates文件夹下建立book文件夹
建立视图
def index_2(request):
    context = {
        'name': '从心',
        'age': '22'
    }

    return render(request, template_name='book/index_2.html', context=c ontext)
建立模板
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>index_2</title>
</head>

<body>
    <div>
        书籍列表
        <ul>
            <li>西游记</li>
            <li>三国演义</li>
        </ul>
    </div>


    <div>
        个人信息
        <div>{{ name }}</div>
        <div>{{ age }}</div>
    </div>

</body>

</html>

配置文件与静态文件

BASE_DIR
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG
DEBUG = True
  • 默认工作在DEBUG模式下
  • 修改源代码程序会自动重启
  • Django程序出现异常时会向前端显示详细的错误追踪信息
DEBUG = False

ALLOWED_HOSTS = ['*']
  • ALLOWED_HOSTS为指定的IP访问白名单
静态文件
  • 在项目根目录下建立static文件夹
  • STATIC_URL是静态文件访问路由
  • STATICFILES_DIRS是静态文件存放路径
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]
  • 通过http://127.0.0.1:8000/static/1.jpg访问静态文件

数据库配置

建立数据库book_manager
  • 字符集:utf8mb4
  • 排序规则:utf8mb4_bin
配置settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': 'localhost',
        'PORT': 3306,
        'USER': 'root',
        'PASSWORD': 'root',
        'NAME': 'book_manager',
    }
}
安装MySQL驱动
  • 配置__init__.py
import pymysql

pymysql.install_as_MySQLdb()
  • 测试运行,修改最后一个链接
if query is not None:
	query = query.encode(errors='replace')
数据插入
insert into book_info (name, pub_date, read_count, comment_count, is_delete) values
('射雕英雄传', '1980-5-1', 12, 34, 0),
('天龙八部', '1986-7-24', 36, 40, 0),
('笑傲江湖', '1995-12-24', 20, 80, 0),
('雪山飞狐', '1987-11-11', 58, 24, 0);
insert into person_info (name, gender, description, book_id, is_delete) values
('郭靖', 0, '降龙十八掌', 1, 0),
('黄蓉', 1, '打狗棍法', 1, 0),
('黄药师', 0, '弹指神功', 1, 0),
('欧阳锋', 0, '蛤蟆功', 1, 0),
('梅超风', 1, '九阴白骨爪', 1, 0),
('乔峰', 0, '降龙十八掌', 2, 0),
('段誉', 0, '六脉神剑', 2, 0),
('虚竹', 0, '天山六阳掌', 2, 0),
('王语嫣', 1, '神仙姐姐', 2, 0),
('令狐冲', 0, '独孤九剑', 3, 0),
('任盈盈', 1, '弹琴', 3, 0),
('岳不群', 0, '华山剑法', 3, 0),
('东方不败', 1, '葵花宝典', 3, 0),
('胡斐', 0, '胡家刀法', 4, 0),
('苗若兰', 1, '黄衣', 4, 0),
('程灵素', 1, '医术', 4, 0),
('袁紫衣', 1, '六合拳', 4, 0);

数据增加

save()方法
from book.models import BookInfo
book_info = BookInfo(
    name='完美世界',
    pub_date='2013-8-16'
)
book_info.save()
objects.create()方法
from book.models import BookInfo
BookInfo.objects.create(
    name='斗破苍穹',
    pub_date='2014-5-4'
)

数据修改

save()方法
from book.models import BookInfo
book_info = BookInfo.objects.get(id=5)
book_info.name = '斗罗大陆'
book_info.save()
objects.filter().update()方法
from book.models import BookInfo
BookInfo.objects.filter(id=6).update(name='炼气十万年')

数据删除

delete()方法
from book.models import BookInfo
book_info = BookInfo.objects.get(id=6)
book_info.delete()
objects.filter().delete()方法
from book.models import BookInfo
BookInfo.objects.filter(id=5).delete()

数据库查询

基础查询
objects.all()方法
from book.models import BookInfo
BookInfo.objects.all()
objects.count()方法
from book.models import BookInfo
BookInfo.objects.all()
objects.exclude()方法
from book.models import BookInfo
BookInfo.objects.exclude(id=1)
objects.filter()方法
from book.models import BookInfo
BookInfo.objects.filter(id=1)[0]
过滤查询
exact
from book.models import BookInfo
BookInfo.objects.get(id__exact=1)
contains
from book.models import BookInfo
BookInfo.objects.filter(name__contains='湖')
endswith
from book.models import BookInfo
BookInfo.objects.filter(name__endswith='部')
isnull
from book.models import BookInfo
BookInfo.objects.filter(name__isnull=True)
in
from book.models import BookInfo
BookInfo.objects.filter(id__in=[1, 3, 5])
gt
from book.models import BookInfo
BookInfo.objects.filter(id__gt=3)
year
from book.models import BookInfo
BookInfo.objects.filter(pub_date__year=1980)
gte
from book.models import BookInfo
BookInfo.objects.filter(pub_date__gte='1990-1-1')
F对象
from book.models import BookInfo
from django.db.models import F
BookInfo.objects.filter(read_count__gt=F('comment_count') * 2)
Q对象
逻辑与
objects.filter()方法
from book.models import BookInfo
BookInfo.objects.filter(read_count__gt=20, id__lt=3)
# BookInfo.objects.filter(read_count__gt=20).filter(id__lt=3)
Q对象
from book.models import BookInfo
from django.db.models import Q
BookInfo.objects.filter(Q(read_count__gt=20) & Q(id__lt=3))
逻辑或
from book.models import BookInfo
from django.db.models import Q
BookInfo.objects.filter(Q(read_count__gt=20) | Q(id__lt=3))
逻辑非
from book.models import BookInfo
from django.db.models import Q
BookInfo.objects.filter(~Q(id=1))
聚合函数
from book.models import BookInfo
from django.db.models import Sum, Max, Min, Avg, Count
BookInfo.objects.aggregate(Sum('read_count'))
排序函数
正序
from book.models import BookInfo
BookInfo.objects.all().order_by('read_count')
倒序
from book.models import BookInfo
BookInfo.objects.all().order_by('-read_count')
关联查询
访问
一对多的访问
from book.models import BookInfo
book = BookInfo.objects.get(id=1)
book.personinfo_set.all()
多对一的访问
from book.models import PersonInfo
person = PersonInfo.objects.get(id=1)
person.book
# person.book_id
person.book.id
过滤查询
多对一的查询
from book.models import BookInfo
book = BookInfo.objects.filter(personinfo__name='郭靖')
book
book = BookInfo.objects.filter(personinfo__description__contains='八')
book
一对多的查询
from book.models import PersonInfo
people = PersonInfo.objects.filter(book__name='天龙八部')
people
people = PersonInfo.objects.filter(book__read_count__gt=20)
people
切片
from book.models import BookInfo
BookInfo.objects.all()[0:2]
分页
from book.models import BookInfo
from django.core.paginator import Paginator
books = BookInfo.objects.all()
paginator = Paginator(books, 2)
page_1_books = list(paginator.page(1))
page_1_books
paginator.num_pages
惰性执行
  • 如果用变量接收查询语句的返回结果,那么查询语句不会立即执行,而是等到调用该变量时执行
from book.models import BookInfo
books = BookInfo.objects.all()
books
缓存
  • 变量的值存放在系统内存中,如果通过变量进行查询,那么不会对数据库进行查询,而是从内存中查询
from book.models import BookInfo
books = BookInfo.objects.all()
[book.id for book in books]
[book.id for book in books]

HttpRequest

路由参数
配置views.py
def url_data(request, cat_id, sku_id):
    print(cat_id, sku_id)

    return HttpResponse('OK!')
配置urls.py
path('<cat_id>/<sku_id>/', views.url_data)
查询字符串
配置views.py
def query_str_data(request):
    print(request.GET)

    a = request.GET.get('a')
    b = request.GET.get('b')
    print(a, b)

    a_list = request.GET.getlist('a')
    print(a_list)

    return HttpResponse('OK!')
url
http://localhost:8000/query_str_data/?a=1&b=2&a=3
表单数据
配置views.py
def form_data(request):
    print(request.POST)

    username = request.POST.get('username')
    password = request.POST.get('password')

    print(username, password)

    return HttpResponse('OK!')
关闭CSRF
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',
]
JSON数据
配置views.py
def json_data(request):
    json_data = request.body
    dict_data = json.loads(json_data)

    print(dict_data['username'], dict_data['age'])

    return HttpResponse('OK!')
请求头数据
配置views.py
def headers_data(request):
    print(request.META)
    print(request.META['CONTENT_TYPE'])
    print(request.method)
    print(request.path)
    print(request.user)

    return HttpResponse('OK!')
转换器
配置converters.py
from django.urls.converters import register_converter


class TelConverter:
    regex = '1[3-9]\d{9}'

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return str(value)


register_converter(TelConverter, 'tel')
配置views.py
import converters


def tel_data(request, tel_data):
    print(tel_data)

    return HttpResponse('OK!')
配置urls.py
path('<tel:tel_data>/',views.tel_data)

HttpResponse

配置views.py
def http_response(request):
    response = HttpResponse(content='OK!', content_type='text/plain', status=200)
    response['key'] = 'value'

    return response

JsonResponse

配置views.py
def json_response(request):
    books_info = [
        {
            'id': 1,
            'name': '射雕英雄传',
            'pub_date': '1980-5-1'
        },
        {
            'id': 2,
            'name': '天龙八部',
            'pub_date': '1986-7-24'
        }
    ]

    return JsonResponse(data=books_info, safe=False)

Redirect

配置views.py
from django.shortcuts import redirect


def redirect_url(request):
    return redirect('https://www.baidu.com')

Cookie

设置Cookie
配置views.py
def set_cookie(request):
    username = request.GET.get('username')
    password = request.GET.get('password')

    print(username, password)

    response = HttpResponse('OK!')
    response.set_cookie('username', username)
    response.set_cookie('password', password)

    return response
获取Cookie
配置views.py
def get_cookie(request):
    print(request.COOKIES)

    username = request.COOKIES.get('username')
    password = request.COOKIES.get('password')

    return HttpResponse(f'username: {username}, password: {password}')

Session

设置Session
配置views.py
def set_session(request):
    username = request.GET.get('username')
    user_id = 1

    request.session['username'] = username
    request.session['user_id'] = user_id

    del request.session['user_id']
    # request.session.clear()
    # request.session.flush()

    request.session.set_expiry(60)

    return HttpResponse('OK!')
获取Session
配置views.py
def get_session(request):
    username = request.session.get('username')
    user_id = request.session.get('user_id')

    return HttpResponse(f'username: {username}, user_id: {user_id}')
保存Session到Redis
配置settings.py
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        }
    }
}

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'

类视图

类视图定义
配置views.py
from django.views import View


class LoginView(View):
    def get(self, request):
        return HttpResponse(f'当前请求为: {request.method}')

    def post(self, request):
        return HttpResponse(f'当前请求为: {request.method}')
配置urls.py
path('login/', views.LoginView.as_view())
多继承
配置views.py
from django.contrib.auth.mixins import LoginRequiredMixin


class OrderLoginView(LoginRequiredMixin, View):
    def get(self, request):
        return HttpResponse('个人中心页面')

    def post(self, request):
        return HttpResponse('个人中心页面')

中间件

中间件定义
配置middleware.py
from django.utils.deprecation import MiddlewareMixin


class TestMiddleware_1(MiddlewareMixin):
    def process_request(self, request):
        print('每次请求前, 进行调用')

        username = request.COOKIES.get('username')
        if username is None:
            print('用户信息不存在')
        else:
            print('用户信息存在')

    def process_response(self, request, response):
        print('每次响应前, 进行调用')

        return response
配置settings.py
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',
    'book.middlewares.TestMiddleware_1'
]
中间件的调用顺序
配置middleware.py
class TestMiddleware_2(MiddlewareMixin):
    def process_request(self, request):
        print('process_request_2: 每次请求前, 进行调用')

    def process_response(self, request, response):
        print('process_response_2: 每次响应前, 进行调用')

        return response


class TestMiddleware_3(MiddlewareMixin):
    def process_request(self, request):
        print('process_request_3: 每次请求前, 进行调用')

    def process_response(self, request, response):
        print('process_response_3: 每次响应前, 进行调用')

        return response
配置settings.py
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',
    'book.middlewares.TestMiddleware_1',
    'book.middlewares.TestMiddleware_2',
    'book.middlewares.TestMiddleware_3'
]

DRF安装与注册

DRF安装
pip install djangorestframework
DRF注册
配置settings.py

标签:models,py,request,笔记,BookInfo,学习,book,django,Django
From: https://blog.csdn.net/from__2024_06_01/article/details/139377786

相关文章

  • 【机器学习】基于tensorflow实现你的第一个DNN网络
    博客导读:《AI—工程篇》AI智能体研发之路-工程篇(一):Docker助力AI智能体开发提效AI智能体研发之路-工程篇(二):Dify智能体开发平台一键部署AI智能体研发之路-工程篇(三):大模型推理服务框架Ollama一键部署AI智能体研发之路-工程篇(四):大模型推理服务框架Xinference一键部署AI智能体......
  • 01梦断代码阅读笔记之一
    作品简介:《梦断代码》是中国科幻作家刘慈欣的一部长篇小说,创作于2008年。这部小说被认为是中国科幻文学中的一颗璀璨明珠,融合了赛博朋克、虚拟现实、人工智能等多个元素,以其引人入胜的情节和深刻的思想内涵吸引了广大读者。主题分析:科技与人性:《梦断代码》在探讨科技与人性......
  • 七、FreeRTOS学习笔记-中断管理
    FreeRTOS学习笔记-中断管理中断:让CPU打断正常运行的程序,转而去处理紧急的事件(程序)中断执行机制,可简单概括为三步:1、中断请求:外设产生中断请求(GPIO外部中断、定时器中断等)2、响应中断:CPU停止执行当前程序,转而去执行中断处理程序(ISR)3、退出中断:执行完毕,返回被打断的程序处,继续......
  • Markdown 学习
    一级标题标题几个#代表几级标题例如:一级标题#内容二级标题##内容最多支持到6级标题字体加粗加粗用两个*包裹斜体斜体用一个*包裹斜体加粗斜体加粗用三个*包裹删除删除线用两个波浪线包裹引用引用引用>内容分割线三个横线符号(-)或星号(*)图片!加[]加()中......
  • 阅读笔记7
    《构建之法》第八章读后感第八章我感受到了软件测试在保证软件质量和可靠性方面的重要性。通过本章的内容,我了解到了软件测试的目标、分类、策略、计划和执行等关键知识和技巧。在阅读中,我意识到软件测试的目标是为了找出软件中的缺陷,这是确保软件质量的关键一环。同时,了解到了......
  • Redis5学习笔记之四:高级特性(持久化、订阅、主从复制、缓存穿透和雪崩)
    4.redis高级特性4.1持久化Redis的数据全部在内存里,如果突然宕机,数据就会全部丢失,因此必须有一种机制来保证Redis的数据不会因为故障而丢失,这种机制就是Redis的持久化机制。Redis有两种持久化的方式:快照(RDB文件)和追加式文件(AOF文件)4.1.1RDB在指定的时间间隔内将内......
  • 字符串笔记
    一.字符串的编码转换type:查看变量类型1.encode()作用:将字符串类型转换为字节类型,的过程称之为编码。语法:字符串.encode()s='吃米饭'`​`byte_e=s.encode()`​`print(byte_e,type(byte_e))` #b'\xe5\x90\x83\xe7\xb1\xb3\xe9\xa5\xad'<class'bytes'>2.decode()......
  • 英语学习笔记27——Mrs. Smith‘s living room
    Mrs.Smith’slivingroom史密斯太太的客厅词汇Vocabularylivingroom客厅都成:living=liveing生活room屋子搭配:inthelivingroom在客厅文化:西方人一般都在起居室活动,所以客厅很大,一般可以一起聊天,看球,下棋什么的。near在……附近【不直接挨着】例......
  • 近年来高光谱深度学习语义分割方法分类及代表性网络
    目录一、卷积神经网络——光谱、空间、光谱-空间CNN1.SSRN(Spectral-SpatialResidualNetwork)2.HybridSN3.A2S2K-ResNet二、图卷积神经网络GCNGCN(GraphConvolutionalNetworksforHyperspectralImageClassification)三、深度置信网络DBN四、循环神经网络RNN......
  • JVM(Java虚拟机)、JMM(Java内存模型)笔记
    面试常见:请你谈谈你对JVM的理解?java8虚拟机和之前的变化更新?什么是OOM,什么是栈溢出StackOverFlowError?怎么分析?JVM的常用调优参数有哪些?内存快照如何抓取?怎么分析Dump文件?谈谈JVM中,类加载器你的认识?请你谈谈你对JVM的理解?JVM(Java虚拟机)是Java程序的运行环境,它允......