[Solved]-Exposing model method with Tastypie

21👍

Within your Game-Resource, you can always prepend new urls that can expose methods. For example (Edited according to the comment by @BigglesZX):

from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash

class GameResource(ModelResource):
    class Meta:
         queryset = Game.objects.all()
         resource_name = 'store'

    def prepend_urls(self):
        """ Add the following array of urls to the GameResource base urls """
        return [
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/start%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('start'), name="api_game_start"),
        ]

    def start(self, request, **kwargs):
         """ proxy for the game.start method """  

         # you can do a method check to avoid bad requests
         self.method_check(request, allowed=['get'])

         # create a basic bundle object for self.get_cached_obj_get.
         basic_bundle = self.build_bundle(request=request)

         # using the primary key defined in the url, obtain the game
         game = self.cached_obj_get(
             bundle=basic_bundle,
             **self.remove_api_resource_names(kwargs))

         # Return what the method output, tastypie will handle the serialization
         return self.create_response(request, game.start())

So now you can call this method using the following uri “/game/[pk]/start/”
So “/game/1/start/” will call the start method of game with pk = 1

Leave a comment