Search code examples
pythondjangoresttastypie

django-tastypie usage without model


I need to POST data via AJAX-request to backend python function (that data will be processed with third-party python script) and use the result in the frontend. Currently I am using django-tastypie for API (I am using only ModelResource for my Models). As I understand, I can use Resource to implement this behaviour, but I am a little confused because I don't want to save or store any data, I just want to procced it in the backend. Should I use django-tastypie or maybe it is better to choose another method?


Solution

  • You can use prepend_urls for this

    prepend_urls -> A hook for adding your own URLs or matching before the default URLs. Useful for adding custom endpoints or overriding the built-in ones. Tastypie docs link

    See below code

    class YourModelResource(ModelResource):
        class Meta:
            queryset = YourModel.objects.all()
            resource_name = 'your_model'
    
        def prepend_urls(self):
            return [
                url(r"^(?P<resource_name>%s)/do_some_work%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('do_some_work'), name="api_do_some_work"),
            ]
    
        def do_some_work(self, request, **kwargs):
            self.method_check(request, allowed=['post'])
            self.is_authenticated(request)
    
            #Call the script and get the results
            results = []
    
            result_list = {
                'results': results,
            }
    
            return self.create_response(request, result_list)
    

    Here prepend_urls method is overridden to call a nested resource do_some_work. The URI for this call will be like this

    /api/v1/your_model/do_some_work/
    

    Above method is suggested if you have to use Tastypie other wise Django views will be best option for this scenario.