Search code examples
djangotastypie

Any way for dehydrate() to share an object during an API call in tastypie?


Is there any way for the dehydrate function in tastypie to share some variable? In any other framework, every request would create a new instance of the class, so we can use self to share data.

My use case: want to dehydrate objects returned by GET list with some additional data, but the request gets heavy due to the repeated db calls. Not everything is from a standard sql db, so prefetch_related will only take me so far.

class Meta:
    queryset = Entry.objects.all()
    list_allowed_methods = ['get', 'post']
    detail_allowed_methods = ['get', 'post', 'put', 'delete']

def dehydrate(self, bundle):
    # # wanted something like this
    # bundle.foo = self.cache['foo']
    # # but self is shared between all requests as an instance 
    # # of this class is declared while initializing, and I want 
    # # self.cache to be recreated for every request (without 
    # # potential races)

urlpatterns = [
    url(r'^api/', include(EntryResource().urls)),
]

Solution

  • In the end, I used bundle.request to save data. Basically:

    try:
        bundle.request.cache
    except AttributeError:
        bundle.request.cache = {}