Django的ListView超详细⽤法(含分页paginate)
开发环境:
python 3.6
django 1.11
场景⼀
经常有从数据库中获取⼀批数据,然后在前端以列表的形式展现,⽐如:获取到所有的⽤户,然后在⽤户列表页⾯展⽰。
解决⽅案
常规写法是,我们通过Django的ORM查询到所有的数据,然后展⽰出来,代码如下:
def user_list(request):
"""返回UserProfile中所有的⽤户"""
django怎么学users = UserProfile.objects.all()
return render(request, 'talks/users_list.html', context={"user_list": users})
这样能够解决问题,但是Django针对这种常⽤场景,提供了⼀个更快速便捷的⽅式,那就是ListView,⽤法如下:
from ic import ListView
class UsersView(ListView):
model = UserProfile
template_name = 'talks/users_list.html'
context_object_name = 'user_list'
这样我们就完成了上边功能,代码很简洁。
场景⼆:
我想要对数据做过滤,ListView怎么实现?代码如下:
from ic import ListView
class UsersView(ListView):
model = UserProfile
template_name = 'talks/users_list.html'
context_object_name = 'user_list'
def get_queryset(self): # 重写get_queryset⽅法
# 获取所有is_deleted为False的⽤户,并且以时间倒序返回数据
return UserProfile.objects.filter(is_deleted=False).order_by('-create_time')
如果你要对数据做更多维度的过滤,⽐如:既要⽤户是某部门的,还只要获取到性别是男的,这时候,可以使⽤Django提供的Q函数来实现。
场景三
我想要返回给Template的数据需要多个,不仅仅是user_list,可能还有其他数据,如获取当前登陆⽤户的详细信息,这时怎么操作?,代码如下:
from ic import ListView
class UsersView(ListView):
model = UserProfile
template_name = 'talks/users_list.html'
context_object_name = 'user_list'
def get_context_data(self, **kwargs): # 重写get_context_data⽅法
# 很关键,必须把原⽅法的结果拿到
context = super().get_context_data(**kwargs)
username = ('user', None)
context['user'] = (username=username
return context
这样,你返回给Template页⾯时,context包含为{'user_list': user_list, 'user': user}。
场景四
我想要限制接⼝的请求⽅式,⽐如限制只能GET访问,代码如下:
from ic import ListView
class UsersView(ListView):
model = UserProfile
template_name = 'talks/users_list.html'
context_object_name = 'user_list'
http_method_names = ['GET'] # 加上这⼀⾏,告知允许那种请求⽅式
场景五
我卡卡卡的返回了所有的数据给前端页⾯,前页⾯最好得分页展⽰呀,这怎么搞?
到此这篇关于Django的ListView超详细⽤法(含分页paginate)的⽂章就介绍到这了,更多相关Django的ListView⽤法内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论