django ListView的使用 ListView中获取url中的参数值方式

(编辑:jimmy 日期: 2024/9/23 浏览:2)

view.py

from django.views.generic import ListView,DetailView
from xxxx.models import Model_Name
class Colortag_view(ListView):
 #context_object_name = '如果不指定的话在html页面中 可以使用object_list获取' 
 context_object_name = 'object_list'
 #template_name='html页面所在目录'
 template_name='caradmin/colortags/colortags.html'
 #自定义查询方法
 def get_queryset(self):
  #获取url 中的值 比如http://127.0.0.1/admin/colortags/"htmlcode">
from . import views
urlpatterns = [
 path('colortags/', views.Colortag_view.as_view(), name = 'modelname_list'),
]

补充知识:Django分类查询和关键字查询以及查询后的分页

思路:分类和关键字查询分为以下几种情况:

1、只按照分类查询

2、值按照关键字查询

3、分类和关键字一起查询

第一种情况,值按照分类查询:

我们写了一个select下拉菜单来进行选择分类,当我们选中某一个分类时,则跳转到相应的分类的商品的展示页面。

<!-- 点击类别跳转到则展示相应的分类 -->
 $("#p_type").change(function(){
 var type = $(this).val()
 location.href = '/backweb/good_list/"htmlcode">
<!-- 关键字查询 -->
function select_goods(){
 var context=$('#context').val()
 var type = $('.select').val()
 
 if (context){
  location.href = '/backweb/good_list/"{% url 'backweb:good_list' %}" rel="external nofollow" >第一页</a>

views代码

def good_list(request):
 if request.method == 'GET':
  page_num = int(request.GET.get('page', 1))
  type = request.GET.get('type',0)
  context = request.GET.get('context','')
  # 如果拿不到分类则将type_id设置为0
  if not type:
   type_id = int(type)
  else:
   type_id = int(type)
  # 所有的分类
  type_list = FoodType.objects.all()
  # 根据相应的分类查找相应的商品
  # 如果type_id不为0则获取相应分类的商品
  if not type_id:
   goods = Goods.objects.all()
  else:
   goods = Goods.objects.filter(goods_type_id=type_id)
 
  # 如果有搜索条件则按照搜索条件模糊查询
  if context:
   goods = Goods.objects.filter(goods_type_id=type_id,productname__contains=context)
   if not goods:
    goods = Goods.objects.filter(goods_type_id=type_id,productname__contains=context[-1])

以上这篇django ListView的使用 ListView中获取url中的参数值方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。