如何在Django Tastypie中调用Resource实例。

时间:2014-11-07 06:30:18

标签: python django tastypie

这是我的tastypie代码段。

我有一个资源,在post_list方法中,正在创建Mysample的实例。

我想调用Mysample实例的方法,请帮我怎么做,

请在代码中找到我需要调用Mysample实例

方法的注释
class MysampleResource(ModelResource):
    intfeild1 = fields.IntegerField('intfeild1_id', null=True)
    intfeild2 = fields.IntegerField('intfeild1_id')

    class Meta:
        always_return_data = True
        queryset = Mysample.objects.all()
        allowed_methods = ['get','post','put','delete',]
        authentication = SessionAuthentication()
        authorization = MysampleAuthorization()


    def post_list(self, request, **kwargs):

            result = super(MysampleResource, self).post_list(request, **kwargs)

            #here I want to call a method of Mysample Instance.
            return result

请帮帮我,我是乞丐,所以请你提出一个建议,告诉我应该采用哪种方法,以及我应该在哪里做。

1 个答案:

答案 0 :(得分:1)

您只需在资源中添加方法:

def test_method(self,param*):
        #Do your stuff
        return result

在post_list中你可以这样称呼它:

self.test_method(param*)

注意:方法声明包括2个参数,但在python" self"作为隐式参数传递,以便当您调用方法时,您不会传递自我对象。

    在这种情况下,
  • =可能不只是一个参数使用","为了将它们分开。

如果我们应用所有以前的概念,您的代码应如下所示:

class MysampleResource(ModelResource):
    intfeild1 = fields.IntegerField('intfeild1_id', null=True)
    intfeild2 = fields.IntegerField('intfeild1_id')

    class Meta:
        always_return_data = True
        queryset = Mysample.objects.all()
        allowed_methods = ['get','post','put','delete',]
        authentication = SessionAuthentication()
        authorization = MysampleAuthorization()


        def post_list(self, request, **kwargs):

                result = super(MysampleResource, self).post_list(request, **kwargs)

                #Let's say that you want to pass resquest as your param to your method
                method_result=self.test_method(request)
                return result

         def test_method(self,request):
                #Do your stuff
                return result