zoukankan      html  css  js  c++  java
  • 饮冰三年-人工智能-Python-24 Django ORM增删改查

    一:首先使用默认的sqlite3创建表


      1:现在在models.py中添加表模型

    from django.db import models
    
    # Create your models here.
    class Book(models.Model):
        name=models.CharField(max_length=20)
        price = models.IntegerField()
        pub_date=models.DateField()
    models.py

      2:在Teminal中通过命令创建表

      python manage.py makemigrations ----------该命令执行后会在migrations中创建0001_initial.py中生成文件 

      python manage.py migrate  ----------该命令执行后会在数据库中生成数据表

    至此,数据库创建成功

    二:使用Mysql创建表


      1:修改配置表 

    """
    Django settings for Django_ORM project.
    
    Generated by 'django-admin startproject' using Django 2.1.4.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/2.1/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/2.1/ref/settings/
    """
    
    import os
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '(%h695j&g^4s(@&hk9#66xye6nrv=y9hr*(1va58(^j%_zmlzw'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'app01.apps.App01Config',
    ]
    
    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',
    ]
    
    ROOT_URLCONF = 'Django_ORM.urls'
    
    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',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'Django_ORM.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/2.1/ref/settings/#databases
    
    # DATABASES = {
    #     'default': {
    #         'ENGINE': 'django.db.backends.sqlite3',
    #         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    #     }
    # }
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'Django_ORM',    #你的数据库名称
            'USER': 'root',   #你的数据库用户名
            'PASSWORD': '12qwaszx!@QWASZX', #你的数据库密码
            'HOST': '', #你的数据库主机,留空默认为localhost
            'PORT': '3306', #你的数据库端口
    
        }
    
    }
    
    # Password validation
    # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/2.1/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.1/howto/static-files/
    
    STATIC_URL = '/static/'
    Setting.py

      2:修改Django_ORM下面的__init__.py文件 (python的数据库驱动引擎,把默认的MySQLdb()替换成pymysql)

        如果事先没有安装pymysql模块 可通过 pip install pymysql命令安装

    import pymysql
    # (python的数据库驱动引擎,把默认的MySQLdb()替换成pymysql)
    pymysql.install_as_MySQLdb()
    __init__.py

      3:继续执行以下命令

      python manage.py makemigrations ----------该命令执行后会在migrations中创建0001_initial.py中生成文件 

      python manage.py migrate  ----------该命令执行后会在数据库中生成数据表

      至此,数据表创建成功

    三、通过orm对表进行增删改查


      在settings加上日志记录部分,就可以方便的看出每条操作所执行的SQL语句了  

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

      1:创建首页  

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
               margin: 0px;
               padding: 0px;
            }
            .head{
                line-height: 40px;
                background-color: green;
                color: white;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div class="outer">
            <div class="head">标题</div>
            <div class="content">
                <a href="/addbook/">添加书籍</a>
                <a href="/updatebook/">修改书籍</a>
                <a href="/deltebook/">删除书籍</a>
            </div>
            <div></div>
        </div>
    </body>
    </html>
    index.html

      2:设置对应urls

    """Django_ORM URL Configuration
    
    The `urlpatterns` list routes URLs to views. For more information please see:
        https://docs.djangoproject.com/en/2.1/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.contrib import admin
    from django.urls import path
    from app01 import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('index/', views.index,name="index"), #创建首页
        path('addbook/', views.addbook,name="addbook"), #新增书籍
        path('updatebook/', views.updatebook, name="updatebook"),  # 新增书籍
        path('deltebook/', views.deltebook, name="deltebook"),  # 新增书籍
    ]
    urls.py

      3:views

    from django.shortcuts import render,HttpResponse
    from app01.models import *
    # Create your views here.
    def index(request):
        return render(request,"index.html")
    def addbook(request):
        # 方式一
        b=Book(name="python",price=80,pub_date="2012-12-12",author="张三")
        b.save()
        # 方式二
        Book.objects.create(name="Linux",price=99,author="李四",pub_date="2011-11-11")
        return HttpResponse("添加成功!")
    def updatebook(request):
        # 方式一
        Book.objects.filter(author="李四").update(price=999)
        # 方式二
        b=Book.objects.get(id=2)
        b.price=888
        b.save()
        return HttpResponse("修改成功!")
    def deltebook(request):
        Book.objects.filter(id=1).delete()
        return HttpResponse("删除成功!")
    views

    from django.shortcuts import render,HttpResponse
    from app01.models import *
    # Create your views here.
    def index(request):
        return render(request,"index.html")
    def addbook(request):
        # 方式一
        b=Book(name="python",price=80,pub_date="2012-12-12",author="张三")
        b.save()
        # 方式二
        Book.objects.create(name="Linux",price=99,author="李四",pub_date="2011-11-11")
        return HttpResponse("添加成功!")
    def updatebook(request):
        # 方式一
        Book.objects.filter(author="李四").update(price=999)
        # 方式二
        b=Book.objects.get(id=2)
        b.price=888
        b.save()
        return HttpResponse("修改成功!")
    def deltebook(request):
        Book.objects.filter(id=1).delete()
        return HttpResponse("删除成功!")
    def querybook(request):
        # ----------返回的是个集合 <class 'django.db.models.query.QuerySet'>----------
        # bookList=Book.objects.all()# 查询所有结果
        # bookList=Book.objects.all()[:2]# 查询结果 支持切片
        # bookList = Book.objects.filter(author='张三')#它包含了与所给筛选条件相匹配的对象
        # bookList = Book.objects.all().exclude(author='张三')#它包含了与所给筛选条件不匹配的对象
        # ----------like------------返回的是个集合 <class 'django.db.models.query.QuerySet'>----------
        # bookList = Book.objects.filter(id__lte=5,id__gt=2)  # 查询所有结果 2<id<=5
        # bookList = Book.objects.filter(id__range=[1,4])  # 查询所有结果 between and
        # bookList = Book.objects.filter(id__in=(1,2))  # 查询所有结果 in
        # bookList = Book.objects.exclude(id__in=(1,2))  # 查询所有结果 not in
        # bookList = Book.objects.filter(name__contains="lin")  #
        # bookList = Book.objects.filter(name__icontains="lin")  #  忽略大小写
        # bookList = Book.objects.filter(name__startswith="lin")  #
        # bookList = Book.objects.filter(name__istartswith="lin")  #  忽略大小写
        # bookList = Book.objects.filter(name__endswith="A")  #
        bookList = Book.objects.filter(name__iendswith="A")  #  忽略大小写
        # ----------返回的是个对象 <class 'app01.models.Book'>----------
        # aBook = Book.objects.get(id=5) # 返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象超过一个或者没有都会抛出错误
        # aBook = Book.objects.first() #  返回第一条记录
        # aBook = Book.objects.last() #  返回最后一条记录
        # ----------对返回结果进行处理----------
        # bookList = Book.objects.all().values("name","author") #只筛选“书名”和“作者”
        # bookList = Book.objects.all().values_list("name", "author") #它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列 <QuerySet [('python', '张三'), ('Linux', '李四'), ('Java', '张三2'), ('Linux2', '李四')]>
        # bookList = Book.objects.all().order_by("price","id") #排序
        # bookList = Book.objects.all().reverse()#对查询结果反向排序,貌似没什么用
        # bookList = Book.objects.all().values("author").distinct()#从返回结果中剔除重复纪录
        # num=Book.objects.all().count()# 返回数据库中匹配查询(QuerySet)的对象数量。
        # num = Book.objects.filter(author='张三111').exists()#  如果QuerySet包含数据,就返回True,否则返回False。
        return render(request,"index.html",locals())
    查询

    四、通过orm对表进行增删改查之一对多 


    from django.shortcuts import render,HttpResponse
    from APP2.models import *
    # Create your views here.
    def index(request):
        return render(request,"index.html")
    def addbook(request):
        # 方式一,通过ID保存
        b=Book(name=".net",price=80,pub_date="2012-12-12",publish_id="1")
        b.save()
        # 方式二,先获取“出版社”实体,再保存
        pub=Publish.objects.get(id=1)
        Book.objects.create(name="Linux",price=99,pub_date="2011-11-11",publish=pub)
        return HttpResponse("添加成功!")
    def updatebook(request):
        # 方式一 更改“清华出版社”下所有书的价格
        Book.objects.filter(publish__name="清华出版社").update(price=999)
        # 方式二 更改id为2的书的出版社名称
        b=Book.objects.filter(id=2)[0].publish
        b.name="新华出版社"
        b.save()
        return HttpResponse("修改成功!")
    def deltebook(request):
        Book.objects.filter(publish__name="新华出版社").delete()
        return HttpResponse("删除成功!")
    def querybook(request):
        # 获取某出版社出版的书
        # ----------方式1:先获取某出版社--->再获取对应的书----------
        # pu=Publish.objects.filter(name="北京大学出版社")[0]
        # bookList=Book.objects.filter(publish=pu)
        # ----------方式2----------
        # bookList = Publish.objects.get(id=1).book_set.all()
        # ----------方式3-双下划线----------
        bookList = Book.objects.filter(publish__name="北京大学出版社")
        # 练习:查询某书的出版社名称
        publishName =Book.objects.filter(name="python").values_list("publish__name")[0]
        publishName=Publish.objects.filter(book__name="python").values_list("name")[0]
        return render(request,"index.html",locals())
    View Code

    五、通过orm对表进行增删改查之多对多 


    from django.db import models
    
    class Book(models.Model):
        name=models.CharField(max_length=20)
        price = models.IntegerField()
        pub_date=models.DateField()
        # 创建一对多的方法
        publish = models.ForeignKey("Publish",on_delete=models.CASCADE)
        # 创建多对多的方法
        authors=models.ManyToManyField("Author")
    class Publish(models.Model):
        name = models.CharField(max_length=32)
        city = models.CharField(max_length=32)
    
    class Author(models.Model):
        name=models.CharField(max_length=32)
        age=models.IntegerField()
    多对多

      

    from django.db import models
    
    class Book(models.Model):
        name=models.CharField(max_length=20)
        price = models.IntegerField()
        pub_date=models.DateField()
        # 创建一对多的方法
        publish = models.ForeignKey("Publish",on_delete=models.CASCADE)
        # 创建多对多的方法
        authors=models.ManyToManyField("Author")
    class Publish(models.Model):
        name = models.CharField(max_length=32)
        city = models.CharField(max_length=32)
    
    class Author(models.Model):
        name=models.CharField(max_length=32)
        age=models.IntegerField()
    models
    from django.shortcuts import render,HttpResponse
    from django.db.models import Avg,Max,Sum,Min,F,Q
    from APP2.models import *
    # Create your views here.
    def index(request):
        return render(request,"index.html")
    def addbook(request):
        # 方式一,通过ID保存
        b=Book(name=".net",price=80,pub_date="2012-12-12",publish_id="1")
        b.save()
        # 方式二,先获取“出版社”实体,再保存
        pub=Publish.objects.get(id=1)
        Book.objects.create(name="Linux",price=99,pub_date="2011-11-11",publish=pub)
        return HttpResponse("添加成功!")
    
    def updatebook(request):
        # 方式一 更改“清华出版社”下所有书的价格
        Book.objects.filter(publish__name="清华出版社").update(price=999)
        # 方式二 更改id为2的书的出版社名称
        b=Book.objects.filter(id=2)[0].publish
        b.name="新华出版社"
        b.save()
        return HttpResponse("修改成功!")
    def deltebook(request):
        Book.objects.filter(publish__name="新华出版社").delete()
        return HttpResponse("删除成功!")
    def querybook(request):
        # 获取某出版社出版的书
        # ----------方式1:先获取某出版社--->再获取对应的书----------
        # pu=Publish.objects.filter(name="北京大学出版社")[0]
        # bookList=Book.objects.filter(publish=pu)
        # ----------方式2----------
        # bookList = Publish.objects.get(id=1).book_set.all()
        # ----------方式3-双下划线----------
        bookList = Book.objects.filter(publish__name="北京大学出版社")
        # 练习:查询某书的出版社名称
        publishName =Book.objects.filter(name="python").values_list("publish__name")[0]
        publishName=Publish.objects.filter(book__name="python").values_list("name")[0]
        return render(request,"index.html",locals())
    
    def addAuthorForBook(request):
        # -------------------多对多开始------------------------
        # 给书籍添加作者2  3  ---添加一个集合
        book_obj = Book.objects.get(id=7)  # 先获取到某本书
        author_obj = Author.objects.filter(id__in=(2,3))  # 获取作者 2 3
        book_obj.authors.add(*author_obj)  # 给书添加作者----添加一个集合
    
        # 给书籍添加作者4   ---添加一个实体
        book_obj.authors.add(Author.objects.get(id=4))
        return HttpResponse("为书籍添加作者成功!")
    def updateAuthorForBook(request):
        # -------------------多对多开始------------------------
        # 直接在author表中修改名字
        b=Book.objects.get(id=7).authors.all()[0]
        b.name="李师师"
        b.save()
        return HttpResponse("为书籍修改作者成功!")
    def deleteAuthorForBook(request):
        # -------------------多对多开始------------------------
        # 移除作者3
        book_obj = Book.objects.get(id=7)  # 先获取到某本书
        book_obj.authors.remove(3)  # 可以进行简写
       #可移除多个
        author_obj = Author.objects.filter(id=2)
        book_obj.authors.remove(*author_obj)
        return HttpResponse("为书籍删除作者成功!")
    def queryAuthorForBook(request):
        # -------------------多对多开始------------------------
        #查询张三出过的书
        bookList = Book.objects.filter(authors__name="张三")
        #查询书本的平均价格
        booksAvgPrice=Book.objects.all().aggregate(Avg("price"))
        # 查询"张三"书的总价格
        booksSumPrice = Book.objects.filter(authors__name="张三").aggregate(总价格=Sum("price"))
        # 求每个人出书的平均价格
        booksAvgPriceForPeople=Book.objects.values("authors__name").annotate(price=Avg("price"))
        # 求各个出版社的最低的价格
        booksPublishMinPrice=Book.objects.values("publish__name").annotate(minprice=Min("price"))
        return render(request,"index.html",locals())
    
    def updatePriceForBook(request):
        Book.objects.all().update(price=F("price")+10)
        return HttpResponse("为书籍添加价格成功!")
    
    def queryPriceForBook(request):
        # -------------------多对多开始------------------------
        #查询张三出过的书,并且价格等于90(Q查询和普通查询一起使用的时候,Q放前面)
        bookList2 = Book.objects.filter(Q(price=90),authors__name="张三")
        # 查询张三出过的书,或者价格等于90
        bookList2 = Book.objects.filter(Q(price=90)|Q(authors__name="张三")).values("id","name","authors__name","price")
        # 查询不是张三出过的书
        bookList2 = Book.objects.filter(~Q(authors__name="张三"))
        #-------------------注意:bookList2为QuerySet类型,懒加载,不使用不会请求数据库---------------
        # -------------------为了减少内存中的缓存可使用--------------------------
        if bookList2.exists():
            print("不想向内存中添加数据,仅仅是判断是否存在")
        #-------------------迭代器--------------------------
        bookList2=bookList2.iterator()
        for ite in bookList2:
            print("转换成迭代器以后,用一次就没有了")
        return render(request,"index.html",locals())
    Views
    """Django_ORM2 URL Configuration
    
    The `urlpatterns` list routes URLs to views. For more information please see:
        https://docs.djangoproject.com/en/2.1/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.contrib import admin
    from django.urls import path
    from APP2 import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('index/', views.index,name="index"), #创建首页
        path('addbook/', views.addbook,name="addbook"), #新增书籍
        path('updatebook/', views.updatebook, name="updatebook"),  # 新增书籍
        path('deltebook/', views.deltebook, name="deltebook"),  # 新增书籍
        path('querybook/', views.querybook, name="querybook"),  # 新增书籍
        path('addAuthorForBook/', views.addAuthorForBook, name="addAuthorForBook"),  # 给书籍添加作者
        path('updateAuthorForBook/', views.updateAuthorForBook, name="updateAuthorForBook"),  # 修改书籍的作者
        path('deleteAuthorForBook/', views.deleteAuthorForBook, name="deleteAuthorForBook"),  # 删除书籍的作者
        path('queryAuthorForBook/', views.queryAuthorForBook, name="queryAuthorForBook"),  # 查询书籍的作者
        path('updatePriceForBook/', views.updatePriceForBook, name="updatePriceForBook"),  # 给书籍添加10元
        path('queryPriceForBook/', views.queryPriceForBook, name="queryPriceForBook"),  # Q查询
    
    ]
    urls
    """
    Django settings for Django_ORM2 project.
    
    Generated by 'django-admin startproject' using Django 2.1.4.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/2.1/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/2.1/ref/settings/
    """
    
    import os
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '5%@&gx+jf88o2(xud0@7nditgvoch%p6#+8e)dx$s7g6n5jdj^'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'APP2.apps.App2Config',
    ]
    
    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',
    ]
    
    ROOT_URLCONF = 'Django_ORM2.urls'
    
    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',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'Django_ORM2.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/2.1/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'Django_ORM',  # 你的数据库名称
            'USER': 'root',  # 你的数据库用户名
            'PASSWORD': '12qwaszx!@QWASZX',  # 你的数据库密码
            'HOST': '',  # 你的数据库主机,留空默认为localhost
            'PORT': '3306',  # 你的数据库端口
    
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/2.1/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.1/howto/static-files/
    
    STATIC_URL = '/static/'
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'console':{
                'level':'DEBUG',
                'class':'logging.StreamHandler',
            },
        },
        'loggers': {
            'django.db.backends': {
                'handlers': ['console'],
                'propagate': True,
                'level':'DEBUG',
            },
        }
    }
    settings
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
               margin: 0px;
               padding: 0px;
            }
            .head{
                line-height: 40px;
                background-color: green;
                color: white;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div class="outer">
            <div class="head">标题</div>
            <div class="content">
                <a href="/addbook/">添加书籍</a>
                <a href="/updatebook/">修改书籍</a>
                <a href="/deltebook/">删除书籍</a>
                <a href="/querybook/">查询书籍</a>
                <br/>
                <a href="/addAuthorForBook/">给书籍添加作者</a>
                <a href="/updateAuthorForBook/">修改书籍的作者</a>
                <a href="/deleteAuthorForBook/">删除书籍的作者</a>
                <a href="/queryAuthorForBook/">查询书籍的作者</a>
                <br/>
                <a href="/updatePriceForBook/">给书籍添加10元(F查询)</a>
                <a href="/queryPriceForBook/">查询书籍(Q查询)</a>
            </div>
            <div>
                {% if bookList.count > 0 %}
                    <table>
                        <tr><td>序号</td><td>书名</td><td>作者</td><td>价格</td></tr>
                        {% for book in bookList %}
                            <tr><td>{{ book.id }}</td><td>{{ book.name }}</td><td>暂无</td><td>{{ book.price }}</td></tr>
                        {% endfor %}
    
                    </table>
                {% endif %}
                查询出一本书所在的出版社:{{ publishName }}
                <br/>
                返回数字:{{ num }}
                <br/>
                多对多查询
                <br/>
                书的平均价格:{{ booksAvgPrice }}
                <br/>
                书的总价格:{{ booksSumPrice }}
                <br/>
                {% if booksAvgPriceForPeople.count > 0 %}
                    <table>
                        <tr><td>作者</td><td>价格</td></tr>
                        {% for authorPrice in booksAvgPriceForPeople %}
                            <tr> <td>{{ authorPrice.authors__name }}</td><td>{{ authorPrice.price }}</td></tr>
                        {% endfor %}
    
                    </table>
                {% endif %}
             <br/>
                {% if booksPublishMinPrice.count > 0 %}
                    <table>
                        <tr><td>出版社</td><td>最低价格</td></tr>
                        {% for publishPrice in booksPublishMinPrice %}
                            <tr> <td>{{ publishPrice.publish__name}}</td><td>{{ publishPrice.minprice }}</td></tr>
                        {% endfor %}
    
                    </table>
                {% endif %}
            <br/>
             {% if bookList2.count > 0 %}
                    <table>
                        <tr><td>序号</td><td>书名</td><td>作者</td><td>价格</td></tr>
                        {% for book in bookList2 %}
                            <tr><td>{{ book.id }}</td><td>{{ book.name }}</td><td>{{ book.authors__name }}</td><td>{{ book.price }}</td></tr>
                        {% endfor %}
    
                    </table>
                {% endif %}
            </div>
        </div>
    </body>
    </html>
    index.html

    六、 总结


    一、必知必会13条

    1:返回具体对象

       get() first() last() 

    2:返回QuerySet

      all() , filter() , exclude() , order_by() , reverse() , distinct()

    3:返回指定字段的QuerySet

      values() values_list()

    4:返回数字 

      count() 

    5:返回布尔值

      exists() 

    二、单表中双下划线

      __gt        # greater than 大于
      __lt          # less than 小于
      __gte       # greater than equal 大于等于
      __lte      #小于等于
      _in        # in
      __range    # 什么范围
      __contains     # like 包含
      __startswith   # 以什么开头
      __endswith    # 以什么结束
      __isnull=True   # 是否为空
      __year      # 年
      __month        # 月

    三、高级操作

      aggregate  #聚合

      annotate    #分组

      F 和 Q

      事务

     ps:更多补充内容请移步饮冰三年-人工智能-Python-48 Django ORM 性能优化

  • 相关阅读:
    Asp.net的HTTP请求处理过程
    通过16道练习学习Linq和Lambda
    学习资料
    .NET处理HTTP请求
    new override virtual 区别与用法
    13个优秀的UML建模工具软件
    做iOS开发程序员10个必需的iOS开发工具和资源[转]
    jQuery的deferred对象详解
    MySQL 5.0存储过程编程入门(转)
    简单谈谈事件与委托(转)
  • 原文地址:https://www.cnblogs.com/YK2012/p/10091788.html
Copyright © 2011-2022 走看看