Search code examples
pythondjangotastypie

How to call in instance of Resource in Django Tastypie.?


Here is my tastypie code snippet.

I have a Resource and in post_list method , an instance of Mysample is getting created there.

I want to call a method of Mysample Instance , Please help me how to do that,

please find the comment in code where I need to call the method of Mysample instance

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

Please help me , I'm begginer, so could you please give suggestion on which method to override and where should I need to do that.


Solution

  • You just need to add your method in your resource:

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

    and within post_list you can call it like:

    self.test_method(param*)
    

    Note: The method declaration include 2 params but in python "self" is passed on as an implicit param so that when you call your method you don't pass on the self object.

    • = could be more than just one parameter in that case use "," in order to separate them.

    If we apply all the previous concepts your code should look like:

    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