dehydrate() 在 API 调用 tastypie 期间共享对象的任何方式?

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

有没有办法让tastypie中的dehydrate函数共享一些变量?在任何其他框架中,每个请求都会创建一个新的 class 实例,因此我们可以使用 self 来共享数据。

我的用例:想要将 GET 列表返回的对象与一些额外的数据一起脱水,但由于重复的数据库调用,请求变得很重。并非所有内容都来自标准 sql 数据库,因此 prefetch_related 只能带我到此为止。

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)),
]

最后我用bundle.request来保存数据。 基本上:

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