问题
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.
I have tried:
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'),
回答1:
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']
)
It is probably better to use devide_id
here, since then it is syntactically clear that we compare identifiers with identifiers.
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']
)
来源:https://stackoverflow.com/questions/52871149/how-to-pass-variable-in-url-to-django-list-view