一、模板层(补充)
'''
{{ }} # 一般是写变量的
{% %} # 一般是写逻辑的
'''
1. 变量的分配
支持python中所有数据类型
2. 过滤器:模板中使用函数
语法: {{obj|过滤器名称:参数}}
过滤器有很多种,不用都掌握,掌握几个常用的就行
default
length
date
safe
二、 模板之标签
'''
就是在模板里面使流程控制:if else elseif for
标签看起来像是这样的: {% tag %}
'''
1.for标签
{% for person in person_list %}
<p>{{ person.name }}</p>
{% endfor %}
注:循环序号可以通过{{forloop}}显示
forloop.counter The current iteration of the loop (1-indexed) 当前循环的索引值(从1开始)
forloop.counter0 The current iteration of the loop (0-indexed) 当前循环的索引值(从0开始)
forloop.revcounter The number of iterations from the end of the loop (1-indexed) 当前循环的倒序索引值(从1开始)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 当前循环的倒序索引值(从0开始)
forloop.first True if this is the first time through the loop 当前循环是不是第一次循环(布尔值)
forloop.last True if this is the last time through the loop 当前循环是不是最后一次循环(布尔值)
forloop.parentloop 本层循环的外层循环
2.遍历字典
{% for key,val in dic.items %}
<p>{{ key }}:{{ val }}</p>
{% endfor %}
{% for foo in d.keys %}
<p>{{ foo }}</p>
{% endfor %}
{% for foo in d.values %}
<p>{{ foo }}</p>
{% endfor %}
3.if 标签
{% if num > 100 or num < 0 %}
<p>无效</p>
{% elif num > 80 and num < 100 %}
<p>优秀</p>
{% else %}
<p>凑活吧</p>
{% endif %}
if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
4.with起别名
d = {'username':'kevin','age':18,'info':'这个人有点意思','hobby':[111,222,333,{'info':'NB'}]}
{% with d.hobby.3.info as nb %}
<p>{{ nb }}</p>
在with语法内就可以通过as后面的别名快速的使用到前面非常复杂获取数据的方式
<p>{{ d.hobby.3.info }}</p>
{% endwith %}
5.csrf_token
<form action="" method="post">
{% csrf_token %}
<input type="submit">
</form>
三、模板的继承(重要)
1.继承:继承之后的页面跟被继承的页面一模一样
{% extends 'index.html' %}
2.继承之后,要自己划分要修改的区域
"""一个页面中应该有三块区域被修改"""
css
js
html
{% block js %}
<script>
alert(123)
</script>
{% endblock %}
{% block css %}
{% endblock %}
3.模板的导入
{% include 'hello.html' %}
四、模型层常见的十几种查询方法
方法:filter all first update delete create
1.增加数据
1.方式1:
models.UserInfo.objects.create(username='jack', password=123)
models.UserInfo.objects.create(username='json', password=543)
models.UserInfo.objects.create(username='py', password=342)
models.UserInfo.objects.create(username='java', password=1234223)
models.UserInfo.objects.create(username='js', password=23123)
2.方式2:
2.查询数据
res = models.UserInfo.objects.filter().all()
print(res)
try:
print(res[0])
print(res[0].username)
print(res[0].password)
except:
pass
或者直接取出第一条
res = models.UserInfo.objects.filter().all().first()
print(res)
取出最后一个
res = models.UserInfo.objects.filter().all().last()
print(res)
res = models.UserInfo.objects.values()
print(res)
res = models.UserInfo.objects.values('id')
print(res)
res = models.UserInfo.objects.values('username')
print(res)
res = models.UserInfo.objects.values('password')
print(res)
res = models.UserInfo.objects.values('username','password','id')
for i in res:
print(i.username)
res = models.UserInfo.objects.values_list('username')
print(res[0])
8.如何查看原生SQL语句
res = models.UserInfo.objects.values('username', 'password', 'id')
print(res)
res = models.UserInfo.objects.order_by('-id', 'age')
print(res)
res = models.UserInfo.objects.all().order_by('-id')
print(res)
res = models.UserInfo.objects.count()
print(res)
res = models.UserInfo.objects.exclude(username='kevin')
'''就是除了username=kevin的都打印出来'''
print(res)
res = models.UserInfo.objects.filter(pk=20).first()
print(res)
五、测试环境的搭建
注意:tests.py的用法
制作django环境
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'day58_dj.settings')
import django
django.setup()
六、查看原生sql语句
往setting.py文件中加入以下代码,之后 **增、删、改、查** 就可以查看原生SQL语句了:
res = models.UserInfo.objects.values('id', 'username', 'password')
print(res)
print(res.query)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level': 'DEBUG',
},
}
}
七、基于双下滑线的查询
res = models.UserInfo.objects.filter(age__gt=35).all()
print(res)
res = models.UserInfo.objects.filter(age__gte=20).all()
print(res)
res = models.UserInfo.objects.filter(age__in=[10, 20, 300]).all()
print(res)
res = models.UserInfo.objects.filter(age__range=[18, 40])
print(res)
res = models.UserInfo.objects.filter(username__contains='s').all()
print(res)
res = models.UserInfo.objects.filter(username__startswith='s').all()
print(res)
res = models.UserInfo.objects.filter(reg_time__month=5, reg_time__year=2023, reg_time__day=1).all()
res = models.UserInfo.objects.filter(reg_time__month=5, reg_time__day=1).all()
print(res)
八、外键字段的查询
1.一对多的查询
图书和出版社是一对多的关系
2.增加一本图书?
外键字段的查询和增加
models.Book.objects.create(title='阿Q自转', price=1000, publish_date='2023-08-01', publish_id=1)
publish_obj = models.Publish.objects.filter(pk=20).first()
try:
publish_obj = models.Publish.objects.get(pk=20)
except:
pass
models.Book.objects.create(title='红楼', price=2000, publish_date='2023-08-02', publish=publish_obj)
models.Book.objects.filter(pk=1).delete()
models.Book.objects.filter(pk=2).update(publish_id=3)
数据准备
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8, decimal_places=2)
publish_date = models.DateField(auto_now_add=True)
publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
authors = models.ManyToManyField(to='Author')
class Publish(models.Model):
name = models.CharField(max_length=32)
addr = models.CharField(max_length=64)
def __str__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)
class AuthorDetail(models.Model):
phone = models.BigIntegerField()
addr = models.CharField(max_length=64)