zoukankan      html  css  js  c++  java
  • Django模型层:单表操作,多表操作,常用(非常用)字段和参数,Django-model进阶

    本文目录:

    一、web应用

    二、模板的导入与继承

    三、静态文件相关

    四、inclusion_tag:返回html片段

    五、模型层

     

    一、web应用

      -s包括两个部分:web服务器+application

      -目前阶段django项目用的web服务器是:wsgiref+application

      -上线会用uwsgi+application

      -web服务器(本质是socket)都实现了wsgi协议

      -wsgi:web服务网关接口,是一个协议

    二、模板的导入与继承

      如何引入静态文件(static目录的配置):

    在setting.py文件中配置:

    # STATICFILES_DIRS名字必须叫它
    STATICFILES_DIRS=[
        os.path.join(BASE_DIR,'static'),
    ]

      模板的导入:

        1.写一个好看的模板

    <div>
        <div class="panel panel-primary">
            <div class="panel-heading">同城交友</div>
            <div class="panel-body">
                联系电话:{{ a }}
            </div>
        </div>
    
        <div class="panel panel-danger">
            <div class="panel-heading">
                <h3 class="panel-title">潮流社区</h3>
            </div>
            <div class="panel-body">
                网站是: <a href="http://www.baidu.com">点我</a>
            </div>
        </div>
    </div>

        2.用在想用的地方

          

    {% include '模板的名字.html' %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
        {% load static %}
        <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.css' %}">
        <link rel="stylesheet" href="{% get_static_prefix %}bootstrap-3.3.7-dist/css/bootstrap.css">
    {#    <link rel="stylesheet" href="/statc999/">#}
    
        <title>Title</title>
        <style>
            .head {
                height: 60px;
                background: #1b6d85;
            }
        </style>
    </head>
    <body>
    <div class="head"></div>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-3">
                {% include 'good.html' %}
    
            </div>
            <div class="col-md-9">
    
            </div>
        </div>
    </div>
    </body>
    </html>

      模板的继承

        -写一个母版,base.html(留一些block(盒子)),留的盒子越多,可扩展性就越高

         

    {% block top %}
          
    {% endblock %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
        {% load static %}
        <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.css' %}">
        <link rel="stylesheet" href="{% get_static_prefix %}bootstrap-3.3.7-dist/css/bootstrap.css">
    {#    <link rel="stylesheet" href="/statc999/">#}
        {% block top %}
    
        {% endblock %}
        <title>Title</title>
        <style>
            .head {
                height: 60px;
                background: #1b6d85;
            }
        </style>
    </head>
    <body>
    <div class="head"></div>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-3">
                {% include 'good.html' %}
                {% block left %}
    
                {% endblock %}
            </div>
            <div class="col-md-9">
                {% block content %}
                <h1>我是母版的内容</h1>
                {% endblock %}
            </div>
        </div>
    </div>
    </body>
    </html>

        使用:

          -在一个新的html中

     

    {% extend ’base.html‘ %}
    扩写留的对应的盒子
    {% block top %}
      扩写的额内容
    {% endblock %}
    {% extends 'base.html' %}
    {% block left %}
        我是首页的内容
        <h1>我是index的h1标签</h1>
        我是首页的内容
    
    {% endblock %}
    {% block content %}
        {{ block.super }}
        <h1>我是index的内容</h1>
        {{ block.super }}
    
        {% load my_tag %}
        {% lqz 5 'egon' %}
    
    {% endblock %}
    index.html案例
    {% extends 'base.html' %}
    
    {% block content %}
        我是订单的内容
        <h1>我是order的h1</h1>
    
        <div>
        {% load my_tag %}
        {% mytest 50 'lqz' %}
        </div>
    {% endblock %}
    {% block top %}
        <link rel="stylesheet" href="/static/css/order.css">
    {% endblock %}
    order.html案例

    注意:

      1.扩写的时候,盒子的位置无所谓,只要名字对应正确,就会正确填充

      2.盒子可以不扩写,不谢就是原来的样子

      3.如果要写实模板盒子中原来的东西,需要

        {{ block.super }} --- 写在哪,原来的内容就放在哪

                

    三、静态文件相关

      1.直接写死的:<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">

      2.用script标签:

        {% load static %}

        <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.css' %}">

      3.用get_stasic_prefix:

        {% load static %}

        <link rel="stylesheet" href="{% 用get_static_prefix %}bootstrap-3.3.7-dist/css/bootstrap.css">

        

    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
        {% load static %}
        <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.css' %}">
        <link rel="stylesheet" href="{% get_static_prefix %}bootstrap-3.3.7-dist/css/bootstrap.css">
    {#    <link rel="stylesheet" href="/statc999/">#}
        {% block top %}
    
        {% endblock %}
        <title>Title</title>
        <style>
            .head {
                height: 60px;
                background: #1b6d85;
            }
        </style>
    </head>

        

    四、inclusion_tag:返回html片段

      1.前面几部跟标签和过滤器一样,在app创建templatetags文件夹创建my_tag.py文件

      2.装饰器:@register.inclusion_tag('inclusion.html',name='lqz'),第一个参数是要操作的模板

    from  django.template import Library
    register=Library()
    
    @register.inclusion_tag('inclusiontag.html',name='lqz')
    def mytest(value,value2):
        ll= [ i for i in range(value)]
        return {'ll':ll,'a':value2}

      3.返回一个字典,字典中的值,可以在inclusion中使用

      4.使用:

        {%load 你写的那个py文件 %}

        {% 函数名字 参数 参数 %}

    五、模型层

      单表操作

        -增加、删除、改:两种方式:queryset对象的方法,book对象的方法

        -改:需要的save()

        -get()方法:查询的数据有且只有一条,如果多,少都会跑出异常

      

      单表查询

          -<1> all():                              查询所有结果
           <2> filter(**kwargs):            它包含了与所给筛选条件相匹配的对象    
           <3> get(**kwargs):              返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象超过一个或者没有都会抛出错误。    
           <4> exclude(**kwargs):      它包含了与所给筛选条件不匹配的对象
           <5> order_by(*field):           对查询结果排序('-id')
           <6> reverse():                     对查询结果反向排序
           <8> count():                       返回数据库中匹配查询(QuerySet)的对象数量。
           <9> first():                           返回第一条记录 
           <10> last():                         返回最后一条记录 
           <11> exists():                     如果QuerySet包含数据,就返回True,否则返回False
           <12> values(*field):            返回一个ValueQuerySet——一个特殊的QuerySet,运行后得到的并不是一系列      model的实例化对象,而是一个可迭代的字典序列
           <13> values_list(*field):      它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列
           <14> distinct():                    从返回结果中剔除重复纪录

      单表基于双下划线的查询

           Book.objects.filter(price__in=[100,200,300])
           Book.objects.filter(price__gt100)
           Book.objects.filter(price__lt=100)
           Book.objects.filter(price__gte=100)
           Book.objects.filter(price__lte=100)
           Book.objects.filter(price__range=[100,200])
           Book.objects.filter(title__contains="python")
           Book.objects.filter(title__icontains="python")
           Book.objects.filter(title__startswith="py")
           Book.objects.filter(pub_date__year=2012)

    import os
    if __name__ == '__main__':
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day81.settings")
        import django
        django.setup()
        from app01 import models
        # 单表的增加两种
        # date类型,传的时候,可以传字符串(格式必须是:2018-06-17),可以传时间对象
        # ret=models.Book.objects.create(name='洪流吗',price=23.7,publish='北京出版社',pub_data='2018-06-17')
        # import datetime
        # ctime=datetime.datetime.now()
        # ret=models.Book.objects.create(name='西游记',price=45.9,publish='南京出版社',pub_data=ctime)
        # 生成对象,再调save方法
        # book=models.Book(name='三国演义',price=46.89,publish='南京出版社',pub_data='2017-08-17')
        # book.save()
        
        
        # 删除(pk代指主键)
        # ret=models.Book.objects.filter(pk=1).delete()
        # book=models.Book.objects.filter(pk=1).first()
        # book.delete()
        
        
        #更新
        # ret = models.Book.objects.filter(pk=2).update(name='ddd')
        # book=models.Book.objects.filter(pk=2).first()
        # book.name='XXX'
        # # 没有update这个方法的
        # # book.update()
        # # 既可以保存,又可以更新
        # book.save()
        
        
        # get方法
        # book = models.Book.objects.filter(pk=2).first()
        # book拿到的是 book对象
        # get查到的数据有且只有一条
        # book=models.Book.objects.get(name='XXX')
        # book=models.Book.objects.get(name='三国演义')
        # print(book.name)
        
        
        #     查询的api(方法)
        # exclude(并列条件必须同时满足,也就是and)
        # book=models.Book.objects.exclude(name='三国演义',price=44)
        # # 必须是queryset对象才有query,它就是原生的sql
        # print(book.query)
        # 如何定义一个支持链式操作的类(每个方法返回的时候,返回对象本身)
        
        
        # 按价格升序排列
        # book=models.Book.objects.all().order_by('price')
        # 倒序排列
        # book = models.Book.objects.all().order_by('-price')
        # print(book.query)
        # # 必须有排序规则(在order_by之后用)才能调用reverse方法
        # book = models.Book.objects.all().order_by('price').reverse()
        # book = models.Book.objects.all().reverse()
        # print(book.query)
        # book=models.Book.objects.all().filter(name='偶露菲').count()
        # book=models.Book.objects.all().count()
        # book=models.Book.objects.all().first()
        # print(book)
        # book=models.Book.objects.all().last()
        # queryset 可以按索引取值,但是不支持负索引
        
        
        # 可以支持切片,其实sql就改了
        # book = models.Book.objects.all()[10:15]
        # book=models.Book.objects.all().filter(name='xx').exists()
        # values :返回结果是queryset对象,里面套字典
        # book=models.Book.objects.all().values('name')
        # for i in book:
        #     print(i.get('name'))
        #     print(i['price'])
        # values :返回结果是queryset对象,里面套元组
        # book=models.Book.objects.all().values_list('name','price')
        # book=models.Book.objects.all().values('price').distinct()
        
        
        # 基于双下划线的模糊查询
        # 在列表范围内
        # book=models.Book.objects.filter(price__in=[44,45])
        # print(book.query)
        # 大于
        # book = models.Book.objects.filter(price__gt=44)
        # 大于等于
        # book = models.Book.objects.filter(price__gte=44)
        # 小于
        # book = models.Book.objects.filter(price__lt=44)
        # print(book)
        # # 小于等于
        # book = models.Book.objects.filter(price__lte=45)
        # 在40--50之间
        # book=models.Book.objects.filter(price__range=[40,50])
        # print(book.query)
        # 包含 python
        # book = models.Book.objects.filter(name__contains='python')
        # 不区分大小写的包含
        # book = models.Book.objects.filter(name__icontains='python')
        # print(book.query)
        # 以XX开通
        # book=models.Book.objects.filter(name__istartswith='X')
        # print(book.query)
        # print(book)
        # book=models.Book.objects.filter(name__endswith='义')
        # print(book.query)
        # book=models.Book.objects.filter(pub_data__year='2017')
        # book=models.Book.objects.filter(pub_data__month='01')
        # book=models.Book.objects.filter(pub_data__day='11')
        book=models.Book.objects.filter(pub_data__year='2017',pub_data__month='08')
    
        print(book.query)
        print(book)
    View Code

        

  • 相关阅读:
    Laex/Delphi-OpenCV
    webbrowser 防止读取 缓存
    tesnsorflow 版本安装错了。 可以这样删除。
    python中%代表什么意思?
    python 访问 网页 获得源码
    3.2.2 break 与 continue 语句
    3.2.1 for循环与while循环的基本语法
    3.2 循环结构
    3.1.2 选择结构的几种形式
    3.1.1 条件表达式
  • 原文地址:https://www.cnblogs.com/wuzhengzheng/p/10273671.html
Copyright © 2011-2022 走看看