MohammadReza moeini
MohammadReza moeini

Reputation: 190

remove all record of a model in Django restfull

I try to remove all records of a model by using API but I get an error how can I do that

View :

@api_view(["DELETE"])
@csrf_exempt
@permission_classes([IsAuthenticated])
def delete_site(request):
    try:
        Site.objects.all().delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
    except ObjectDoesNotExist as e:
        return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND)
    except Exception:
        return JsonResponse({'error': 'Something went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

URL

router.register('site-delete',views.delete_site)

Error :

    assert queryset is not None, '`basename` argument not specified, and could ' \
AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute.

Upvotes: 0

Views: 101

Answers (2)

MohammadReza moeini
MohammadReza moeini

Reputation: 190

API for delete all record in a model

View :

@api_view(["DELETE"])
@csrf_exempt
@permission_classes([IsAuthenticated])
def delete_site(request):
    user = request.user.id
    try:
        evnt = Site.objects.all()
        evnt.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
    except ObjectDoesNotExist as e:
        return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND)
    except Exception:
        return JsonResponse({'error': 'Something went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

Add View to router.urls

urlpatterns = [

    # Site
    path('sitedelete/', views.delete_site, name='sitedelete')
    ]+router.urls

Upvotes: 0

gdef_
gdef_

Reputation: 1936

If you are going to use routers you need to use ViewSets, not function based views.

Change your url config to be a path instead:

path(
    "site-delete",
    view= views.delete_site,
    name="delete_site",
),

Or refactor your view as a ViewSet

Upvotes: 1

Related Questions