Django模型类(一)

一、django使用mysql数据库配置

# setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',  # 数据库服务ip地址
        'PORT': '3306',  # 数据库服务占用端口号
        'NAME': 'django_t',  # 库名
        'USER': 'root',  # 用户名
        'PASSWORD': '123456',  # 密码
        'OPTIONS': {
            'charset': 'utf8mb4',  # 字符编码
        },
    }
}

二、在终端展示ORM转换的sql语句(日志配置)

# setting.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

三、创建一个模型类

开发环境

Python == 3.6.13
django == 2.2.24
mysqlclient == 2.0.3

Django项目初始化

python -m django startproject my_book_project   (或 django-admin startproject my_book_project;建议使用前者,原因:如果有虚拟环境,避免系统环境存在django-admin导致虚拟环境调用脚本出错)
cd my_book_project
python manage.py startapp book

创建一个模型类

- book 
    - models.py

from django.db import models

class Book(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    state = models.BooleanField()
    pub_date = models.DateField()
    price = models.DecimalField(max_digits=8, decimal_places=2)
    publish = models.CharField(max_length=32)

    class Meta:
        db_table = 'book_info'  # 对表进行重命名,如果没有加这两行,表的名字为:"app名_类名小写"
模型类字段与sql字段类型对应关系——django模型字段参考 :https://docs.djangoproject.com/zh-hans/3.2/ref/models/fields/#autofield

把存在模型类的app注册到setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'book',
]

执行数据库迁移命令

python manage.py makemigrations
python manage.py migrate

查看book表创建语法

show create table book;

| book  | CREATE TABLE `book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(32) NOT NULL,
  `state` tinyint(1) NOT NULL,
  `pub_date` date NOT NULL,
  `price` decimal(8,2) NOT NULL,
  `publish` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |

模型类对应sql

四、创建一个模型类调试接口

- my_book_project
  - urls.py

from django.contrib import admin
from django.urls import path, include

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

from django.urls import path
from book import views

urlpatterns = [
    path('book/', views.test_orm),
]
- my_book_project
  - book
    - views.py

from django.shortcuts import HttpResponse

def test_orm(request):
    pass

五、使用ORM进行单表的增加操作

启动django服务

python manage.py runserver 8080
访问 http://127.0.0.1:8000/book/

方式1:插入一条书籍数据

from django.shortcuts import HttpResponse
from book.models import Book

def test_orm(request):
    # book_obj = 主键值
    book_obj = Book.objects.create(title="Django红宝书", state=True, price=100, publish="清华出版社", pub_date="2020-12-12")   # 有返回值
    return HttpResponse('ok')

查看控制台

(0.000) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.000) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.002) INSERT INTO `book` (`title`, `state`, `pub_date`, `price`, `publish`) VALUES ('Django红宝书', 1, '2020-12-12', '100.00', '清华出版社'); args=['Django红宝书', True, '2020-12-12', '100.00', '清华出版社']
[06/Jul/2021 08:53:29] "GET /book/ HTTP/1.1" 200 2

方式2:插入一条书籍数据

from django.shortcuts import HttpResponse
from book.models import Book

def test_orm(request):
    book_obj = Book(title="js红宝书", state=True, price=200, publish="北京出版社", pub_date="2020-11-11")  # 没有返回值
    book_obj.save()
    return HttpResponse('ok')

查看控制台

(0.000) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.000) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.001) INSERT INTO `book` (`title`, `state`, `pub_date`, `price`, `publish`) VALUES ('js红宝书', 1, '2020-11-11', '200.00', '北京出版社'); args=['js红宝书', True, '2020-11-11', '200.00', '北京出版社']
[06/Jul/2021 09:09:56] "GET /book/ HTTP/1.1" 200 2

六、使用ORM进行单表的查询操作

6.1、查询所有记录:

from django.shortcuts import HttpResponse
from book.models import Book

def test_orm(request):
    book_obj = Book.objects.all()
    print(f'查询表中所有的记录QuerySet:{book_obj}')
    return HttpResponse('ok')

控制台

(0.000) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.000) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book`  LIMIT 21; args=()
[06/Jul/2021 09:19:29] "GET /book/ HTTP/1.1" 200 2
查询表中所有的记录QuerySet:<QuerySet [<Book: Book object (6)>, <Book: Book object (7)>]>

6.2、精准匹配查询

from django.shortcuts import HttpResponse
from book.models import Book


def test_orm(request):
    book_obj = Book.objects.get(title='js红宝书')  # 返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象超过一个或者没有都会抛出错误。
    print(f'get方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(title='Django红宝书')  # 它包含了与所给筛选条件相匹配的对象
    print(f'filter方法查询,QuerySet:{book_obj}')
    return HttpResponse('ok')

控制台

get方法查询,QuerySet:Book object (6)
filter方法查询,QuerySet:<QuerySet [<Book: Book object (7)>]>
(0.000) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`title` = 'js红宝书'; args=('js红宝书',)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`title` = 'Django红宝书'  LIMIT 21; args=('Django红宝书',)
[06/Jul/2021 09:29:35] "GET /book/ HTTP/1.1" 200 2

6.3、模糊匹配

import datetime

from django.shortcuts import HttpResponse
from book.models import Book


def test_orm(request):
    book_obj = Book.objects.filter(price__in=[100, 200])  # IN
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(price__gt=100)  # 大于 >
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(price__gte=100)  # 大于等于 >=
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(price__lt=200)  # 小于 <
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(price__lte=200)  # 小于等于 <=
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(price__range=[100, 200])  # BETWEEN
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(title__contains="Django")  # LIKE '%Django%'
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(title__icontains="django")  # 不区分大小写 LIKE '%django%'
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(title__startswith="Django")  # LIKE 'Django%'
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(title__istartswith="JS")  # 不区分大小写 LIKE 'JS%'
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(title__endswith="红宝书")  # LIKE 'Django%'
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(title__iendswith="红宝书")  # 不区分大小写 LIKE 'JS%'
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(pub_date=datetime.date(2020, 12, 12))  # 日期精准匹配
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(pub_date__gte=datetime.date(2020, 12, 12))  # 日期大于等于某天
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(pub_date__year=2020)  # 查询某年
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(pub_date__month=12)  # 查询某月
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(pub_date__day=11)  # 查询某天
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(pub_date__isnull=True)  # isnull
    print(f'filter方法查询,QuerySet:{book_obj}')

    book_obj = Book.objects.filter(title__regex='^j')  # regex
    print(f'filter方法查询,QuerySet:{book_obj}')

    return HttpResponse('ok')

控制台

(0.000) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.000) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`price` IN (100, 200)  LIMIT 21; args=(Decimal('100'), Decimal('200'))
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`price` > 100  LIMIT 21; args=(Decimal('100'),)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`price` >= 100  LIMIT 21; args=(Decimal('100'),)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`price` < 200  LIMIT 21; args=(Decimal('200'),)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`price` <= 200  LIMIT 21; args=(Decimal('200'),)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`price` BETWEEN 100 AND 200  LIMIT 21; args=(Decimal('100'), Decimal('200'))
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`title` LIKE BINARY '%Django%'  LIMIT 21; args=('%Django%',)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`title` LIKE '%django%'  LIMIT 21; args=('%django%',)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`title` LIKE BINARY 'Django%'  LIMIT 21; args=('Django%',)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`title` LIKE 'JS%'  LIMIT 21; args=('JS%',)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`title` LIKE BINARY '%红宝书'  LIMIT 21; args=('%红宝书',)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`title` LIKE '%红宝书'  LIMIT 21; args=('%红宝书',)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`pub_date` = '2020-12-12'  LIMIT 21; args=('2020-12-12',)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`pub_date` >= '2020-12-12'  LIMIT 21; args=('2020-12-12',)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`pub_date` BETWEEN '2020-01-01' AND '2020-12-31'  LIMIT 21; args=('2020-01-01', '2020-12-31')
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE EXTRACT(MONTH FROM `book`.`pub_date`) = 12  LIMIT 21; args=(12,)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE EXTRACT(DAY FROM `book`.`pub_date`) = 11  LIMIT 21; args=(11,)
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`pub_date` IS NULL  LIMIT 21; args=()
(0.000) SELECT VERSION(); args=None
(0.000) SELECT `book`.`id`, `book`.`title`, `book`.`state`, `book`.`pub_date`, `book`.`price`, `book`.`publish` FROM `book` WHERE `book`.`title` REGEXP BINARY '^j'  LIMIT 21; args=('^j',)
[06/Jul/2021 10:30:29] "GET /book/ HTTP/1.1" 200 2
posted @ 2021-07-06 18:31  深圳-逸遥  阅读(106)  评论(0编辑  收藏  举报