get_object() method of GenericAPIView class (rest_framework/generics.py line: 88-98)
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
assert lookup_url_kwarg in self.kwargs, (
'Expected view %s to be called with a URL keyword argument '
'named "%s". Fix your URL conf, or set the `.lookup_field` '
'attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
)
filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs)
Since we are using self.lookup_field as keyword argument for filtering so self.lookup_url_kwarg doesn't have any use case as we are not using it for keyword argument.
filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
For example: lookup_url_kwarg = 'slug' doesn't work
Edited for formatting (@rpkilby)
Hi @atikbappy.
self.lookup_field defines what model field is used when querying the object.self.lookup_url_kwarg defines what URL kwarg to get from the view's initialized kwargs. Often these two values are the same, so the local lookup_url_kwarg will default to self.lookup_field if self.lookup_url_kwarg is not defined.
If you've only provided self.lookup_url_kwarg, then the query will look like .filter(pk='some-slug'), when you're probably looking for .filter(slug='some-slug'). You need to set the lookup_field. eg,
class MyView(GenericAPIView):
lookup_field = 'slug'
Most helpful comment
Hi @atikbappy.
self.lookup_fielddefines what model field is used when querying the object.self.lookup_url_kwargdefines what URL kwarg to get from the view's initialized kwargs.Often these two values are the same, so the local
lookup_url_kwargwill default toself.lookup_fieldifself.lookup_url_kwargis not defined.If you've only provided
self.lookup_url_kwarg, then the query will look like.filter(pk='some-slug'), when you're probably looking for.filter(slug='some-slug'). You need to set thelookup_field. eg,