Django(六)

模板语法之标签

        # 在模板html中使用if else for

        {% for foo in l %}
            <p>
        {#     {{ forloop }}#}
                {% if forloop.first %}
                    第一次
                {% elif forloop.last %}
                    最后一次
                {% else %}
                    {{ foo }}
                {% endif %}
            </p>
        {% endfor %}

        {% for foo in user_dict.keys %}
           <p>
            {{ foo }}
           </p>
        {% endfor %}

        {% for foo in user_dict.values %}
            <p>
                {{ foo }}
            </p>
        {% endfor %}

        {% for foo in user_dict.items %}
            <p>
            {{ foo }}
            </p>
        {% endfor %}

模板继承

        # 一个页面被其他页面公共使用
        {% block css %}
            <style>
                h1  {

                }

                .div1 {
                    color: red;
                }
            </style>
        {% endblock %}

        {% block js %}
            <script>
                alert(1243)
            </script>
        {% endblock %}

测试环境搭建

        # 配置环境
        在test.py文件中
        import os

        if __name__ == "__main__":
            os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day06.settings")
            import django
            django.setup()
            # 代码都要写在这个下面
            from app01 import models

ORM查询方法

           from app01 import models

            # get方法
            # models.Book.objects.create(title='西游记',price=111)
            # models.Book.objects.create(title='三国演义',price=111)
            # models.Book.objects.create(title='水浒传',price=111)
            # 1. all, first()
            # res = models.Book.objects.all().first()
            # res = models.Book.objects.all().last() # 最后一个
            # print(res)

            # 2. get
            # res = models.Book.objects.filter(pk=1).first() # None
            '''一般不推荐使用get方法'''
            # res = models.Book.objects.get(pk=11)  # 查询的数据必须存在,不存在直接报错
            # print(res)

            # 3. exclude
            # res = models.Book.objects.exclude(pk=1) # 查询pk=1之外的数据,其实就是排除数据

            # 4. order by
            # select *from t1 order by id asc, price desc, title asc

            # res = models.Book.objects.order_by('id')  # 默认是升序
            # res = models.Book.objects.order_by('-id', 'price')  # 默认是降序
            # 5. 翻转

            # res = models.Book.objects.order_by('id').reverse()  # 默认是降序
            # print(res)

            # 6. count
            # sql: select count(1) from t1
            # res = models.Book.objects.filter(price=100).count()
            # print(res)

            # 7. exists
            # res = models.Book.objects.filter(pk=1).first()

            # 8. values()
            # sql:select title, price from t1

            # 掌握
            # res = models.Book.objects.values('title', 'price') # 列表套字典
            # res1 = models.Book.objects.values_list('title', 'price') # 列表套元祖
            #
            # print(res)
            # print(res1)

            # 去重:一定不加主键,因为主键特点就是唯一且非空
            #sql: select distinct id from t1
            res = models.Book.objects.values('title', 'price').distinct()

基于双下滑线的查询

        # 基于双下滑线的查询
            # 1. 查询书籍价格大于200的
            # sql: select * from t1 where price > 200
            # ORM:gt => greater than equal # 大于等于
            # res = models.Book.objects.filter(price__gt=200).all()
            # res = models.Book.objects.filter(price__gte=200).all()
            # print(res)

            #2. 查询书籍价格小于200的
            # res = models.Book.objects.filter(price__lt=200).all()
            # res1 = models.Book.objects.filter(price__lte=200).all()
            # print(res)
            # print(res1)

            # 3. 查询书籍价格是111, 200的所有书籍
            # sql:select * from t1 where price = 111 or price = 200
            # sql:select * from t1 where price in (111, 200)
            # in走索引,not in 不走索引
            # res = models.Book.objects.filter(price__in=[111, 200]).all()
            # print(res)

            # 4. 查询书籍价格在100-300之间的
            # sql:select * from t1 where price >= 100 and price <= 300
            # sql: select *from t1 where price between 100 and 300
            # 顾头顾尾
            # res = models.Book.objects.filter(price__range=[100, 300]).all()
            # print(res)
            # 5. 查询书籍名称带有西的所有书籍
            # like查询不走索引
            # es: elasticsearch
            # sql:select * from t1 where title like '西%'
            # res = models.Book.objects.filter(title__contains='西').all()
            # 返回结果一定是queryset对象,才能点query属性
            # print(res.query)  # 查看SQL语句
            # print(res)
            '''
                select book.id, book.title from t1

                create table db1.t (id int, name varchar(16))
            '''

            # 6. 查询以西开头结尾的数据
            res = models.Book.objects.filter(title__startswith='西').all()
            res = models.Book.objects.filter(title__endswith='西').all()

            # 7. 以时间查询: 2021-10-5
            res = models.Book.objects.filter(create_time__year=2021, create_time__month=10,create_time__day=5)

查看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',
                },
            }
        }
上一篇:Django(五)


下一篇:Django | 模板的继承与导入