Search code examples
pythondjangoresttastypie

Deleting a queryset using tastypie


Tastypie allows deleting objects on resource list.

http://django-tastypie.readthedocs.org/en/v0.9.9/interacting.html#deleting-a-whole-collection-of-resources

I want to delete a subset of a resource. Assuming I have an api endpoint of /api/foo/, I want to do a DELETE to /api/foo/ with a list of pks and only those objects be deleted, not all objects in the collection.

Is there a way to do this with tastypie?


Solution

  • You can add url by using prepend_urls that is responsible to perform deletion.

    Like in your class following two methods will be added .

    Modify code according to your need . Here I performed authentication first .

    def prepend_urls(self):
        params = (self._meta.resource_name, trailing_slash())
        return [
            url(r"^(?P<resource_name>%s)/delete%s$" % params, self.wrap_view('foo_delete'), name="api_foo_delete")
        ]
    
        ## (?P<resource_name>%s)  will be /api/foo  if your resource name is foo
    
    def foo_delete(self, request, **kwargs):
        """ 
        Get pks to delete from post . 
        pks = request.POST.getlist('pks[]') 
        you can use split if you are sending pks by comma separated .
        pks = (request.POST.get('pks')).split(',')
        """
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        if request.user and request.user.is_authenticated():
            ### perform delete operation of pk . 
            return self.create_response(request, { 'success': True })
        else:
            return self.create_response(request, { 'success': False, 'error_message': 'You are not authenticated, %s' % request.user.is_authenticated() })