barciewicz
barciewicz

Reputation: 3793

How to get serialized API view data into another view?

What is the best way to get DRF API view data into another Django view?

Currently I am just calling the view through requests module:

response = requests.get('my_api_view')

but is there a cleaner way?

I can also just instantiate the API view class in another view, but this will give me unserialized objects.

Upvotes: 0

Views: 1321

Answers (2)

Ken4scholars
Ken4scholars

Reputation: 6296

I'm not sure what exactly you want to achieve but wanting to call a view from another view maybe a sign of bad architecture. It could mean that you have a business logic implemented in the second view which you want to access in the first. Usually the rule of thumb is to move such a common logic somewhere else so it could be used by different views. Again I don't know what you want to achieve but this is a possibilty.

Upvotes: 1

Saad Aleem
Saad Aleem

Reputation: 1745

Not sure what you mean by getting unserialized objects. You can do the following if you're using function-based views:

def view(request):
    # some stuff done
    return Response(<result>)

def another_view(request)
    return view(request)

If you're views are class based then you can do the following:

class AClassBasedView(SomeMixin, SomeOtherMixin):

    def get(self, request):
        # do something with the request
        return Response(<some result>)


class AnotherClassBasedView(SomeMixin, SomeOtherMixin):

    def compute_context(self, request, username):
        #some stuff here here                        
        return AnotherClassBasedView.as_view()(request)

Both of these will return a <class 'rest_framework.response.Response'> object which can be passed further.

Upvotes: 1

Related Questions