I am trying to override delete action in my CategoryViewSet, the build in delete action taked the id of the category DELETE ..category/1/
, but I want it to delete by the slug argument DELETE ..category/movie/
. I can not figure out how can I withdraw slug field from the url (*args)
models.py
class Category(models.Model):
name = models.CharField(
max_length=255,
verbose_name='Category Name'
)
slug = models.SlugField(
unique=True,
verbose_name='Slug Name',
max_length=50
)
serializers.py
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name', 'slug')
views.py
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
def destroy(self, request, *args, **kwargs):
try:
slug = args[0]
delete_category = Category.objects.filter(slug=slug)
self.perform_destroy(delete_category)
except Http404:
pass
return Response(status=status.HTTP_204_NO_CONTENT)
urls.py
router_v1.register(
r'categories',
CategoryViewSet
)
urlpatterns = [
path('', include(router_v1.urls))
]
CodePudding user response:
You have to set non default lookup_field
. Do it in your serializers
and views
.
serializers:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
...
lookup_field = 'slug'
views:
class CategoryViewSet(viewsets.ModelViewSet):
...
lookup_field = 'slug'