学习模板

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)###只查询name
Day_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')





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值