Exposing model method with Tastypie

半腔热情 提交于 2019-12-02 19:35:07

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!