如何将url中的变量传递给Django List View [英] How to pass variable in url to Django List View
问题描述
我有一个Django通用列表视图,我想根据输入到URL中的值进行过滤.例如,当有人输入mysite.com/defaults/41时,我希望视图过滤所有匹配41的值.我已经通过基于功能的视图实现了几种方法,但是没有基于类的Django视图.
I have a Django generic List View that I want to filter based on the value entered into the URL. For example, when someone enters mysite.com/defaults/41 I want the view to filter all of the values matching 41. I have come accross a few ways of doing this with function based views, but not class based Django views.
我尝试过:
views.py
class DefaultsListView(LoginRequiredMixin,ListView):
model = models.DefaultDMLSProcessParams
template_name = 'defaults_list.html'
login_url = 'login'
def get_queryset(self):
return models.DefaultDMLSProcessParams.objects.filter(device=self.kwargs[device])
urls.py
path('<int:device>', DefaultsListView.as_view(), name='Default_Listview'),
推荐答案
亲爱的, self.kwargs
是一本字典,将 strings 映射到提取的相应值从URL中获取,因此您需要在此处使用包含'device'
的字符串:
You are close, the self.kwargs
is a dictionary that maps strings to the corresponding value extracted from the URL, so you need to use a string that contains 'device'
here:
class DefaultsListView(LoginRequiredMixin,ListView):
model = models.DefaultDMLSProcessParams
template_name = 'defaults_list.html'
login_url = 'login'
def get_queryset(self):
return models.DefaultDMLSProcessParams.objects.filter(
device_id=self.kwargs['device']
)
在这里使用 devide_id
可能更好,因为这样在语法上明确了我们将标识符与标识符进行比较.
It is probably better to use devide_id
here, since then it is syntactically clear that we compare identifiers with identifiers.
进行 super()
调用可能也更惯用",这样,如果以后添加mixins,它们可以预处理" get_queryset
致电:
It might also be more "idiomatic" to make a super()
call, such that if you later add mixins, these can "pre-process" the get_queryset
call:
class DefaultsListView(LoginRequiredMixin,ListView):
model = models.DefaultDMLSProcessParams
template_name = 'defaults_list.html'
login_url = 'login'
def get_queryset(self):
return super(DefaultsListView, self).get_queryset().filter(
device_id=self.kwargs['device']
)
这篇关于如何将url中的变量传递给Django List View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!