While working with Django/Django Rest Framework, I noticed an inconsistency in how URL parameters are acccessed in class-based-views.
Problem Description
In Generic Class Based Views, I can access URL parameters in two different ways - depending on the method:
- Trough the positional arguments: For example in the get method, I can access URL parameters as a positional arguments passed directly to method:
#urls.py
path('test/<str:param1>/<int:param2>/', MyView.as_view())
#views.py
class MyView(View):
def get(self, request, param1, param2):
return JsonResponse({'param1': param1, 'param2': param2})
Trough self.kwargs attribute For example when i want to access the same parameters in the get_queryset method, I have to use self.kwargs
#views.py
class MyView(ListView):
model = MyModel
def get_queryset(self):
param1 = self.kwargs.get('param1')
param2 = self.kwargs.get('param2')
return MyModel.objects.filter(field1=param1, field2=param2)
- Trough self.kwargs attribute For example when i want to access the same parameters in the get_queryset method, I have to use self.kwargs
#views.py
class MyView(ListView):
model = MyModel
def get_queryset(self):
param1 = self.kwargs.get('param1')
param2 = self.kwargs.get('param2')
return MyModel.objects.filter(field1=param1, field2=param2)
**I know that i can access url parameters from kwargs anywhere but it leads me to some questions**