1👍
✅
ViewSets
allows you to combine ListView
and DetailView
into one view.
So you don’t need two different views to handle the both actions.
Now if you want to use slug in the url instead of the id
by default, you just have to specify lookup_field
in the serializer and the view like this :
serializers.py
class ProductSerializer(serializers.ModelSerializer):
image = serializers.ImageField(required=True)
class Meta:
model = Product
fields = ("name", "description", "slug", "id", "price", "stock", "image", "category")
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}
views.py
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all().order_by('name')
serializer_class = ProductSerializer
lookup_field = 'slug'
urls.py
router = routers.DefaultRouter()
router.register(r'', ProductViewSet)
urlpatterns = [
url(r'', include(router.urls)),
]
Now you can query http://localhost:8000/
for products list and http://localhost:8000/product_slug
for product detail with product_slug
as slug.
More about Django ViewSets and Routers
Source:stackexchange.com