1、字符串显示
#coding:utf-8
from django.shortcuts import render
# Create your views here.
def index(request):
s=u"欢迎来到python世界"
return render(request,"home.html",{'string':s})###用字典的方式表示传递一个字符串到html,html文件中直接使用{{string}}调用变量
################################################################################################
2、列表显示
#coding:utf-8 from django.shortcuts import render def index(request): for_list=['alex','ray','python','coll'] return render(request,'home.html',{'for_list':for_list})###views.py中列表也是通过字典传递,在home.html文件中使用{% for xx in for_list%} 和{% endfor %}显示列表值
##################################################################################################
3、字典显示
#coding:utf-8 from django.shortcuts import render def index(request): for_dictlist={'alex':u'你好','ray':'python'} return render(request,'home.html',{'for_dictlist':for_dictlist})###views.py中列表也是通过字典传递,在home.html文件中使用{{for_dictlist.alex}}和{{for_dictlist.ray}}显示字典值
#################################################################################################
4、views.py内部循环
#coding:utf-8 from django.shortcuts import render def index(request): for_dictlist={'alex':u'你好','ray':'python'} for_list = map(lambda x:x*x,range(10)) return render(request,'home.html',{'for_list':for_list})
4、查看执行的sql
print(str(Day_list.objects.all().query))
print(str(Day_list.objects.filter(name="").query))
5、values_list 获取元组结果
days=Day_list.objects.values_list('name','age')
days= Day_list.objects.values_list('name', flat=True)###只查询nameDay_list.objects.filter(name='alex').values_list('age', flat=True)###只查询某个人的年龄
6、 values 获取字典结果
days=Day_list.objects.values('name','age')
7、extra 实现 别名,条件,排序等
tags = Tag.objects.all().extra(select={'tag_name': 'name'})
8、annotate 聚合 计数,求和,平均数等
Article.objects.all().values('author_id').annotate(count=Count('author')).values('author_id', 'count')
Article.objects.values('author_id').annotate(avg_score=Avg('score')).values('author_id', 'avg_score')
Article.objects.values('author__name').annotate(sum_score=Sum('score')).values('author__name', 'sum_score')