Skip to content Skip to sidebar Skip to footer

Arguments Of Detailview Methods And Usage Of Pk_url_kwarg

I'm currently watching a course on Django and wondering about the following code: class RestaurantDetailView(DetailView): queryset = Restaurant.objects.all() def get_conte

Solution 1:

As a Django user, def get_context_data(self, *args, **kwargs): and def get_object(self, *args, **kwargs): look unusual to me. The code will work because the same args and kwargs are passed to super(). You could argue that it makes the code more robust because it will still work if Django changes the signature in a future version. However I would prefer to use the same signatures as the parent class.

You are correct that you could use pk_url_kwarg instead of overriding get_object. The pk_url_kwarg should be the name of the kwarg in the URL pattern, so in this case it should be pk_url_kwarg = 'rest_id'. The advantage of pk_url_kwarg is that it simplifies the code. The disadvantage is that it's less obvious how the object is being fetched if you're not familiar with Django's class-based-views.

There's a couple more changes you could make. Instead of queryset = Restaurant.objects.all() you can simply set model, because get_queryset defaults to self.model.objects.all().

Finally, the get_context_data method doesn't do anything apart from printing, so I would remove it entirely once I'd finished debugging.

Putting that together, you get:

classRestaurantDetailView(DetailView):
    model = Restaurantpk_url_kwarg='rest_id'

Post a Comment for "Arguments Of Detailview Methods And Usage Of Pk_url_kwarg"