DjangoORM单表实例

Posted 礁之

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DjangoORM单表实例相关的知识,希望对你有一定的参考价值。

文章目录


此文章参考菜鸟教程:Django ORM – 单表实例 | 菜鸟教程 (runoob.com)

Django版本:

>>> django.VERSION  
(4, 1, 0, 'final', 0)

PS:基于前几章的进度进行修改

一、Django ORM 单表实例

  • 之前在Django模型章节中简单的了解ORM,包括创建数据表,增加、修改、删除数据等,之后几章都会继续了解ORM实例

  • 下面创建一个新的项目app1

#终端执行,创建app1数据模型
django-admin startproject app1 
  • 修改app1/app1/settings.py文件
——————————————————————————————————
ALLOWED_HOSTS = ['*']

——————————————————————————————————
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app1_model',  #添加将要创建的数据模型
]
——————————————————————————————————
#指定数据库
DATABASES = 
    'default': 
    
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'app1',
        'HOST': '10.10.11.218',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123456',
    

——————————————————————————————————
#修改字符、时区
LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_TZ = True
——————————————————————————————————
  • app1/app1/__init__.py文件导入mysql模块
import pymysql
pymysql.install_as_MySQLdb()
  • 在mysql数据库上创建数据库,记得指定数据库编码==(可以使用Nacicat创建,指定utf8和utf8_general_ci的排序规则)==
mysql> create database app1 default charset=utf8;
Query OK, 1 row affected (0.00 sec)

创建新模型

  • 终端执行,创建模型app1_model
#在第一层app1目录执行
django-admin startapp app1_model
  • 修改app1/app1_model/models.py文件
# -*- coding: utf-8 -*-
from django.db import models

class Book(models.Model):
    id = models.AutoField(primary_key=True)     #id会自动闯进啊
    title = models.CharField(max_length=32)		#书籍名称
    price = models.DecimalField(max_digits=5,decimal_places=2)	#书籍价格
    publish = models.CharField(max_length=32)	#出版社名称
    pub_date = models.DateField()	#出版时间
  • 终端执行,创建表结构

注意:注意要在manage.py目录下执行,如果执行错的话,可以先把app1_model目录中的migrations子目录删除,然后到正确目录执行

(test) PS F:\\django\\app1> python .\\manage.py migrate  #创建表的主结构
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK
    
    
    
(test) PS F:\\django\\app1> python .\\manage.py makemigrations app1_model  #提交app1_model的修改
Migrations for 'app1_model':
  app1_model\\migrations\\0001_initial.py
    - Create model Book
    
    
    
(test) PS F:\\django\\app1> python .\\manage.py migrate app1_model  #创建app1_model的表结构
Operations to perform:
  Apply all migrations: app1_model
Running migrations:
  Applying app1_model.0001_initial... OK
  • 查看mysql数据库,成功创建
mysql> use app1;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_app1             |
+----------------------------+
| app1_model_book            |
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
11 rows in set (0.00 sec)

mysql> show create table app1_model_book;
+-----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table           | Create Table                                                                                                                                                                                                                                                        |
+-----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| app1_model_book | CREATE TABLE `app1_model_book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(32) NOT NULL,
  `price` decimal(5,2) NOT NULL,
  `publish` varchar(32) NOT NULL,
  `pub_date` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
  • 当前目录结构

二、数据库操作

(1)添加数据

  • 配置路由,app1/app1/urls.py
from django.contrib import admin
from django.urls import path
from . import views  #导入视图

urlpatterns = [
    path('admin/', admin.site.urls),
    path('add_book/',views.add_book),  #添加路由
]
  • 数据库添加数据,这里菜鸟教程提供两种方法,分别是
  1. 模型实例化对象
  2. 通过ORM提供的objects中的方法
  • 这里使用第二种。创建视图文件,/app1/app1/views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    books = models.Book.objects.create(title='九阴神功',price=200,publish='功夫出版社',pub_date='1777-10-10')  
    print(books,type(books))
    return HttpResponse('<p>数据添加成功!</p>')
  • 现在在终端启动django项目
(test) PS F:\\django\\app1> python .\\manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
September 06, 2022 - 15:06:52
Django version 4.1, using settings 'app1.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CTRL-BREAK.
  • 访问127.0.0.1:8000/add_book

  • 查看数据库,发现成功添加(我这里编码有问题,所以显示乱码了)

  • 查看终端输出,可以发现输出的第一个就是之前admin管理平台的那种格式

  • 根据上述方法,添加多条数据

(2)查找数据

  • 使用all()方法查询所有数据,返回QuerySet类型数据,类似于列表,里面存放一个个模型类的对象,可以使用索引下标取出模型类的对象,实例:
- 修改app1/app1/views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    books = models.Book.objects.all()
    print(books,type(books))
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试,查看终端输出,可以发现books输出了一个QuerySet


  • 查看具体字段可以使用for循环
# -*- coding: utf-8 -*-
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    books = models.Book.objects.all()
    for i in books:
        print(i.title)
        print(i.price)
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试,查看终端输出

- filter()

  • filter()方法用于查询符合条件的数据,返回QuerySet类型数据,实例:
- 修改app1/app1/views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    books = models.Book.objects.filter(pk=3)  #pk代表主键,即筛选主键等于3的数据,相当于id=3
    print(books)
    print("------------------------------")
    books = models.Book.objects.filter(publish="金庸出版社")  #筛选publish字段为金庸出版社的数据
    print(books,type(books))
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试,查看终端输出

  • 可以添加多个条件
- 修改app1/app1/views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    books = models.Book.objects.filter(pk=3)
    print(books)
    print("------------------------------")
    books = models.Book.objects.filter(publish="金庸出版社",price=200)
    print(books,type(books))
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试

  • 使用for循环可以查看数据实例
# -*- coding: utf-8 -*-
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    books = models.Book.objects.filter(pk=3)
    #print(books)
    for i in books:
        print(i.title)
        
    print("------------------------------")
    books = models.Book.objects.filter(publish="金庸出版社",price=200)
    for i in books:
        print(i.title)
        
    #print(books,type(books))
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试

- exclude()

  • exclude()方法用于查询不符合条件的数据,同样返回QuerySet数据类型,实例:
# -*- coding: utf-8 -*-
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    books = models.Book.objects.exclude(publish="金庸出版社")
    for i in books:
        print(i.title)
    #print(books,type(books))
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试

- get()

  • get()方法用于查询符合条件的返回模型类的对象,符合条件的对象只能有一个,如果符合筛选条件的对象超过一个或者没有,都会抛出错误,实例:
# -*- coding: utf-8 -*-
from statistics import mode
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    #三个查询代码依次执行
    books = models.Book.objects.get(pk=2)
    #books = models.Book.objects.get(pk=5)
    #books = models.Book.objects.get(price=200)
    print(books,type(books))
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试


# -*- coding: utf-8 -*-
from statistics import mode
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    #books = models.Book.objects.get(pk=2)
    books = models.Book.objects.get(pk=5)
    #books = models.Book.objects.get(price=200)
    print(books,type(books))
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试,发现报错,这是因为主键id没有等于5的

# -*- coding: utf-8 -*-
from statistics import mode
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    #books = models.Book.objects.get(pk=2)
    #books = models.Book.objects.get(pk=5)
    books = models.Book.objects.get(price=200)
    print(books,type(books))
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试,因为price字段等于200的有两条数据,返回了两个,所以报错了


- order_by()

  • order_by()方法用于对查询结果进行排序,返回QuerySet类型数据
  • 注意:
  1. 参数的字段名要加引号
  2. 降序是在字段前面加一个杠-
  • 实例:
# -*- coding: utf-8 -*-
from statistics import mode
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    books = models.Book.objects.order_by("price")
    #books = models.Book.objects.order_by("-price")
    print(books)
    for i in books:
        print(i.price)
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试

# -*- coding: utf-8 -*-
from statistics import mode
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    #books = models.Book.objects.order_by("price")
    books = models.Book.objects.order_by("-price")
    print(books)
    for i in books:
        print(i.price)
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试

- reverse()

  • reverse()方法用于对查询结果进行反转,返回QuerySet数据类型,实例:
# -*- coding: utf-8 -*-
from statistics import mode
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    #books = models.Book.objects.order_by("price")
    books = models.Book.objects.order_by("-price").reverse()
    print(books)
    for i in books:
        print(i.price)
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试

# -*- coding: utf-8 -*-
from statistics import mode
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    books = models.Book.objects.order_by("price").reverse()
    #books = models.Book.objects.order_by("-price").reverse()
    print(books)
    for i in books:
        print(i.price)
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试

- count()

  • count()方法用于查询数据的数量,返回的是整数,实例:
# -*- coding: utf-8 -*-
from statistics import mode
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    books = models.Book.objects.count()
    #books = models.Book.objects.filter(price=200).count()
    print(books)
    return HttpResponse('<p>查找成功!</p>')
  • 访问测试

  • 也可以统计条件查询的数据量
# -*- coding: utf-8 -*-
from statistics import mode
from django.shortcuts import render,HttpResponse
from app1_model import models

def add_book(request):
    #books = models.Book.objects.create(title="九阴神功",price=200,publish="功夫出版社",pub_date="1777-10-10")  
    #books = models.Book.objects.count()
    books 以上是关于DjangoORM单表实例的主要内容,如果未能解决你的问题,请参考以下文章

DjangoORM单表实例

DjangoORM单表实例

软件开发程序员的“九阳神功”——设计模式

DjangoORM多表实例

DjangoORM多表实例

DjangoORM多表实例